What is dependency injection and when/why should or shouldn’t it be used?

Will give it a try. Hope you are conversant with programming. 😉
Basics
Consider you have a class which depends on another one for a fetching some information from database.
 
1. class MyClass
2. {
3.      private DbConnector dataGetter;
4.      public MyClass()
5.      {
6.           dataGetter = new DbConnector("Db Address");
7.      }
8.      public double CalculateSomething()
9.     {
10.         double dbData = dataGetter.GetSomedata();
11.         return dbData*500;
12.     }
13. }
14. 

 
Looks fine, Isn't it?
 
Now let's write some unit tests for this class.
Unit tests shall test a unit separatly. But if we try to unit test this, we depend on actual database. This is problem no. 1
 
Few days later, we have a better DbConnector as in DbConnectorSuper. We need to search all it's usage and replace the new alongwith constructor parameters etc. Lot of work. this is problem no. 2
 
From above two we can see that there is hard dependency of MyClass on DbConnector. You can term this as problem no. 3 or the root problem. Also this may violet D of SOLID (object-oriented design).
 
How can we ease this? Dependency Injection to the rescue.
 
Now consider following
1. class MyClass
2. {
3.      private IDbConnector dataGetter;
4.      public MyClass(IDbConnector concretDbConnector)
5.     {
6.         dataGetter = concretDbConnector;
7.     }
8.     public double CalculateSomething()
9.    {
10.        double dbData = dataGetter.GetSomedata();
11.        return dbData*500;
12.    }
13. }

 
The concrete implementation is replaced by an abstraction IDbConnector. This is called Dependency Injection (actually Constructor Injection to be specific). This will resolve all the problems stated above.
 
Advanced
Now, there are methods to achieve this. One is simple programmatic way. Whenever we require to instantiate MyClass, We create an Instance of  IDbConnector and inject it in MyClass. This can be a factory for MyClass which is configured to create Myclass for DbConnector.

1. IDbConnector dbConnector = new DbConnector("Db Address");
2. MyClass myClass = new MyClass(dbConnector);

 
Taking this simple method to more advanced level is concept of IoC (Inversion of control, Inversion of Control Containers and the Dependency Injection pattern) frameworks such as Ninject, Unity , Castle.Windsor, Autofac, StructureMap (http://stackoverflow.com/questio…, Comparing .NET DI (IoC) Frameworks, Part 1). They allow you to specify the Dependency Injection in a config file or programmatically and take responsibility of creating a class object with proper dependency.
e.g. In case of Unity, following code bootstraps the creation of MyClass,
 
1. UnityContainer container = new UnityContainer();
2. container.RegisterType<IDbConnector , DbConnector>(new InjectionConstructor("Db Address"));
3. container.RegisterType<IMyClass, MyClass>();

 
And whenever we need to create MyClass,
1. IMyClass myClass = container.Resolve<IMyClass>();

 
Probably you are clear about "why" of dependency injection now. And I think it shall be used wherever there is dependency on some external service. It is ok not to use it if there is dependency on the classes internal to a module (generally a dll or a group of classes in same namespace).
 
Further Reading
For a very detailed understanding, follow the links below
Dependency injection
Inversion of Control Containers and the Dependency Injection pattern
http://stackoverflow.com/questio&#8230;
Dependency Injection
 
and whole book dedicated to it Dependency Injection in .NET
 
Hope this helps.

Answer by Amol Gawai:

Will give it a try. Hope you are conversant with programming. 😉
Basics
Consider you have a class which depends on another one for a fetching some information from database.
 

class MyClass
{
     private DbConnector dataGetter;
     public MyClass()
     {
          dataGetter = new DbConnector("Db Address");
     }
     public double CalculateSomething()
    {
        double dbData = dataGetter.GetSomedata();
        return dbData*500;
    }
}
 

 
Looks fine, Isn't it?
 
Now let's write some unit tests for this class.
Unit tests shall test a unit separatly. But if we try to unit test this, we depend on actual database. This is problem no. 1
 
Few days later, we have a better DbConnector as in DbConnectorSuper. We need to search all it's usage and replace the new alongwith constructor parameters etc. Lot of work. this is problem no. 2
 
From above two we can see that there is hard dependency of MyClass on DbConnector. You can term this as problem no. 3 or the root problem. Also this may violet D of SOLID (object-oriented design).
 
How can we ease this? Dependency Injection to the rescue.
 
Now consider following

class MyClass
{
     private IDbConnector dataGetter;
     public MyClass(IDbConnector concretDbConnector)
    {
        dataGetter = concretDbConnector;
    }
    public double CalculateSomething()
   {
       double dbData = dataGetter.GetSomedata();
       return dbData*500;
   }
}

 
The concrete implementation is replaced by an abstraction IDbConnector. This is called Dependency Injection (actually Constructor Injection to be specific). This will resolve all the problems stated above.
 
Advanced
Now, there are methods to achieve this. One is simple programmatic way. Whenever we require to instantiate MyClass, We create an Instance of  IDbConnector and inject it in MyClass. This can be a factory for MyClass which is configured to create Myclass for DbConnector.

IDbConnector dbConnector = new DbConnector("Db Address");
MyClass myClass = new MyClass(dbConnector);

 
Taking this simple method to more advanced level is concept of IoC (Inversion of control, Inversion of Control Containers and the Dependency Injection pattern) frameworks such as Ninject, Unity , Castle.Windsor, Autofac, StructureMap (http://stackoverflow.com/questio…, Comparing .NET DI (IoC) Frameworks, Part 1). They allow you to specify the Dependency Injection in a config file or programmatically and take responsibility of creating a class object with proper dependency.
e.g. In case of Unity, following code bootstraps the creation of MyClass,
 

UnityContainer container = new UnityContainer();
container.RegisterType<IDbConnector , DbConnector>(new InjectionConstructor("Db Address"));
container.RegisterType<IMyClass, MyClass>();

 
And whenever we need to create MyClass,

IMyClass myClass = container.Resolve<IMyClass>();

 
Probably you are clear about "why" of dependency injection now. And I think it shall be used wherever there is dependency on some external service. It is ok not to use it if there is dependency on the classes internal to a module (generally a dll or a group of classes in same namespace).
 
Further Reading
For a very detailed understanding, follow the links below
Dependency injection
Inversion of Control Containers and the Dependency Injection pattern
http://stackoverflow.com/questio…
Dependency Injection
 
and whole book dedicated to it Dependency Injection in .NET
 
Hope this helps.

What is dependency injection and when/why should or shouldn't it be used?

Advertisements

Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s