Saturday, 6 April 2013

Dependency Injection & How structure map work(s) in LAYMAN terms


        You are aware of the word Structure map,Castle Windsor and Spring.Net, but you still can’t tell people you know what it actually does? We all have used in all our project that are designed now.

You always come across Dependency Injection and Inversion of control principle and we know these technology jargons are related to the structure map.

So I thought, to put through a list of questions that will help you better understand the concepts of Dependency injection and Inversion of control (IOC) concepts.

 Assuring you, after reading this blog you will have better understanding about the dependency injection & IOC as whole, with its concepts, principles and usages.







How structure map works?


Where is dependency injection mainly used?

Can we have projects without dependency injection?


What is coupling?

            Let’s start with STORY to understand coupling better. As we know about the Luxury segment car Toyoto-Lexus and Cadillac cars. Early 20th century, Japanese cars started taking over US car markets especially in luxury segments. Cadillac wants to know why this happens, so they bought a Lexus car and started dismantling the parts, it was to the surprise of the Cadillac engineers they did not need an extra hammer or fender to dismantle the car, adding to the surprise they assembled back the car without a hammer and fender.
                       
            Secret behind the Toyota’s car is that they have designed the car so that there is less coupling between each and every parts, so it can be easily removed from each other.

            Same principle can be applied in our software industry, if there is less coupling between two different entities then we can be sure that maintenance and enhancement are easier.


What is Dependency Injection? Why does it matter to me?


Laymen’s term

            I don’t have to care about creating instance of an object; somebody will take care of creating an instance


            When you need to consume other object, you need reference of them to use their properties and method. So two classes have to be coupled in one way or another, so it one can consume other.

Customer example

            Let us consider the customer example where customer class which depends on order and order class depends on products

In below example the Customer has to initiate the Orders and orders has initiate to Products, so whenever there is change in the product the Orders has to be changed, and whenever there is change in order customer class has to be changed.


public class Customer
    {
      private IOrders order;

       public Customer()
        {
            order = new Orders();
       }
    }

public class Orders : IOrders
  {
        private IProducts product;
      public Orders()
      {
          product = new Products();
      }
 }


                        In order to break the above dependency of creating objects we go for dependency injection, rather than the class creates an instance of other object, we inject the instance to object that needs an instantiation.


    public class Customer
    {
Order Instance Injected to IOrder
        private IOrders order;

        public Customer()
        {
            order = new Orders();
        }
    }

  public class Orders : IOrders
  {
       
Product Instance Injected to IProduct

      private IProducts product;
      public Orders()
      {
          product = new Products();
      }
   }

Dependency will be handled by other party who will take care of injecting the dependency to the object, so the classes are less coupled. So it can be interfaced with any other class of the same type.


Principles used in Dependency Injection & IOC?

It covers two principles mainly

  • Single Responsibility Principle
  • Open and Closed principle
  • Hollywood principle (Don’t call us we will call you)

            We will see with an example when we cover other important question below.


What are the underlying benefits of dependency injection?

            The notable and distinguished benefits of dependency injection are

·        Testable code
·        Reduced Dependencies
·        Reusable Code

Testable Code
           
            Code become testable because the class dependency is injected into the components which means the mock test data can also be injected into the component, which makes the code more testable.

Reduced Dependencies

            Dependency injection eliminates or reduces the dependency between two components. Any component is vulnerable to dependency chances, if the dependency changes the components also have to change.

            Using above customer example, when the order class adds one more parameter to the constructor we need to change customer class to accommodate the change of number of parameters in customer class.

            If the dependency is injected through an Injection mechanism then the parameter change does not change the customer class all we need to change is the injection mechanism which will take care of the entire place where the order class is used.
         
Reusable Code

            Code become reusable because the code which takes care of dependency injection is used everywhere.

                       

Where exactly it can be used in our projects?

            It can be used in places where the code should be

·        Unit Testable
·        Framework Classes
     
How Structure map works?


                        When a class needs to use an object then the class needs to create an instance, the duty of instance creation will be take care by dependency injection.

Class will not create an instance for any class that they are dependent on. The instance will be injected by other source.

Different types of injection are

1. Constructor Injection
2. Setter Injection
3. Interface Injection

Let us consider Structure map as an example since it is widely used and it is an old dependency injector. Structure map dll will scan for any dll and it own implementation in a config file or in a config class.

In config file or config class, there will be mapping for the object vs. the interface. The information consists of which class should be mapped to which interface for dependency injection.
Structure map reads the scan method and then create instances according to the config or class definition. If the ICustomer class is configured to customer, then where ever it finds the usage of ICustomer in any class, structure map dll will inject the instance of customer object.
             
There are also default rules for any dependency injection

    If there are any classes "XXX" that use the interface "IXXX" which starts with "I", then the structure map will scans for all the assembly for "xxxx" class and instantiates automatically.

 For example, if you have IProduct used in your class then you need not add config entry or class definition for structure map. Structure map will automatically scan for Product class removing the "I" from the interface name. 
Any other special type of injection needed for special cases must be taken care the developer, such as the instance created based on the type or value of an object or any complex instance creation which is need by the project must be written as separate code for scanning


What is Inversion of control?

            Inversion of control is based on Hollywood principle - “Don’t call us we will call you”. In Inversion of control, external interfaces are called instead, they calling our code, the control is being inverted.

            Inversion of control is used mainly in framework projects where the projects do not call the framework method instead we will call the project interfaces method to perform duties that are due.

           Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

Dependency injection vs. Inversion of control

            There are lots of confusion that exists between dependency injection and inversion of control. Comparing DI and IOC is like comparing apples to oranges. Dependency injection can be inverted for injection operation and does not mean dependency injection implicitly implement inversion of control and either inversion of control has to be dependency injected.

Dependency injection

            Core purpose is to Inject dependency to the class so the class operate does not have to perform the instantiation operation

            Primary purpose is to have loosely coupled object

            Dependency can be configured and be part of the integral core of the project.


Inversion of control
           
            Higher level classes and lower level classes should not be dependant on each other; both should be depend on abstraction.

            They are used implemented in framework project to follow Hollywood principle. For eg:- Plugin Classes

             IOC can be used to been implemented using subscriber and publisher where the external interface can subscribe to the events


Where is dependency injection mainly used?

            Dependency injection is used in projects where there is need to create a framework and all the components and services should be a plug-in. It is better not to use dependency injection if your project is not framework project and it does not need to be pluggable. IOC principle can be achieved using service locator.

Can we have projects without dependency injection?

            It is perfectly normal to have project without dependency injection, just because the dependency injection words sound fancy, doesn't mean we have to use in our project. We have other options such as service locator which will be give us clear understandable code because it looks same as instantiating the object in the class but the implementation details is hidden.

For further reading please visit the url http://martinfowler.com/articles/injection.html

Build Bot using LUIS