Dependency Injection: Part 1

In this Article I am going to discuss about "Dependency injection" on which I am working and exploring. In this article I am going to discuss about what is dependency injection and why there is need of this software design pattern.

Dependency injection

To understand dependency injection better way, let’s consider below code, 

  1. Public class client  
  2. {  
  3.      Public static void main()  
  4.      {  
  5.         NeedDependencyClass a = new NeedDependencyClass();  
  6.      }  
  7. }  
  8.   
  9. public class NeedDependencyClass  
  10. {  
  11.   Private readonly DependencyClass _b;  
  12.   public NeedDependencyClass ()  
  13.   {  
  14.      _b = new DependencyClass();  
  15.   }  
  16.   public void Test()  
  17.   {  
  18.      _b.Test();  
  19.   }  
  20. }  
  21.   
  22. public class DependencyClass  
  23. {  
  24.   public void Test()  
  25.   {  
  26.     // code for text method  
  27.   }  
  28. }  

In above code class client creates NeedDependencyClass and use it, then class NeedDependencyClass consume service of class DependencyClass to perform task i.e. class NeedDependencyClass is depend on class DependencyClass to perform task. This kind of the code is hardcoded dependency.

Image above shows the representation of creation and use of the objects.

 


 
 
Problem with code is
  1. Class NeedDependencyClass itself responsible for creating its own dependency.
  2. Code is tightly coupled, because dependency cannot be replaceable.
  3. Code also violate “Open Closed” rule of SOLID principal which says that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". Because do changes in the Test method I need to modify DependencyClass.
  4. Testing of Class NeedDependencyClass becomes difficult as I cannot replace Dependency class DependencyClass with other dependency.

Dependency injection is software development pattern which introduced to resolve above problems.

Definition of this pattern is: Remove hard coded dependency and make it possible to replace at run-time or compile time.

In following section I am going to describe how problem listed above get resolved with the Dependency injection pattern.

Solution

1)Make client i.e. first class in dependency graph which consume service to create all dependent object

Resolution to the first problem of code above, pass the responsibility of supplying all required dependency to the first in dependency graph i.e. client class which is first class of the dependency graph.

So the code will change like this

  1. Public class client  
  2. {  
  3.      Public static void main()  
  4.      {  
  5.         NeedDependencyClass a = new NeedDependencyClass(new DependencyClass());  
  6.       }  
  7. }  
  8.   
  9. public class NeedDependencyClass  
  10. {  
  11.   Private readonly DependencyClass _b;  
  12.   public NeedDependencyClass(DependencyClass b)  
  13.   {  
  14.      _b = b;  
  15.   }  
  16.   public void Test()  
  17.   {  
  18.      _b.Test();  
  19.   }  
  20. }  
  21.   
  22. public class DependencyClass  
  23. {  
  24.   public void Test()  
  25.   {  
  26.     // code for text method  
  27.   }  
  28. }  

Image below shows object creation only done by client class object and others class down the line use supplied defendant object.

 

 

 

2)Removes tight coupling between object i.e allow to define loose coupling

To understand the second problem better way, let’s consider with the real life scenario of Computer or laptop.

 

 

As you can see in the above image we have the port for each device external device to which I can associate external device and do our work.

But problem with this is I cannot attach my keybord on printer port and vice versa, same problem occurs with the other devices. So this is like tight coupling that I cannot change my external device on the give interface i.e. on which I am depends.

Solution to this is USB port.

If I have USB port than I can easily attach any device to my machine and perform my task.

 

 

 

What is tight coupling between classes? (In programming)

Let start with simple example:

  1. public class NeedDependencyClass  
  2. {  
  3.   Private readonly DependencyClass _b;  
  4.   public NeedDependencyClass(DependencyClass b)  
  5.   {  
  6.      _b = b;  
  7.   }  
  8.   public void Test()  
  9.   {  
  10.      _b.Test();  
  11.   }  
  12. }  
  13.   
  14. public class DependencyClass  
  15. {  
  16.   public void Test()  
  17.   {  
  18.     // code for text method  
  19.   }  
  20. }  

Now as you see in above code class NeedDependencyClass utilized class DependencyClass, this means that class NeedDependencyClass is depend on class DependencyClass. This type of dependency is tight dependency between class NeedDependencyClass and class DependencyClass. Because class DependencyClass is passed as parameter to class NeedDependencyClass and class NeedDependencyClass utilizing method of class DependencyClass. Now if the why it called as tightly coupled. If code is like this to create

  1. NeedDependencyClass a = new NeedDependencyClass(new DependencyClass());   

now if I created class DependencyClass1 like as follows public

  1. class DependencyClass1 {   
  2.       public void Test()   
  3.       { //code for text method }   
  4. }  

and I want to pass DependencyClass1 instead of DependencyClass in class and want to call test method

  1. NeedDependencyClass a = new NeedDependencyClass(new DependencyClass1());   

This will give compiler error because I am trying to pass DependencyClass1 object as parameter. So this means Class NeedDependencyClass cannot accept any another class than Class DependencyClass.

Solution to this problem is define and interface as below which get implemented by classes

 

  1. Interface IDependencyClass  
  2. {  
  3.    Void Test();  
  4. }  
  5.   
  6. Class DependencyClass : IDependencyClass  
  7. {  
  8.  ……  
  9. }  
  10. Class DependencyClass1 : IDependencyClass  
  11. {  
  12.  ……  
  13. }  

So the code become like this

 

  1. public class NeedDependencyClass  
  2. {  
  3.   Private readonly IDependencyClass _b;  
  4.   public NeedDependencyClass(IDependencyClass b)  
  5.   {  
  6.      _b = b;  
  7.   }  
  8.   public void Test()  
  9.   {  
  10.      _b.Test();  
  11.   }  
  12. }  

And this code will work both the class DependencyClass and DependencyClass1

Image below shows DependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class DependencyClass.

3) Make your class depend on Abstraction

Now there is requirement like only authenticated user of the application can run Test method in the application, than developer of the class need to modify the Test method like this.

  1. public class DependencyClass : IDependencyClass  
  2. {  
  3.   public void Test()  
  4.   {  
  5.     using(PrincipalContext pc = new PrincipalContext(ContextType.Domain,   
  6.         "YOURDOMAIN"))  
  7.  {  
  8.       bool isValid = pc.ValidateCredentials("myuser",   
  9.        "mypassword");  
  10.                if(isValid)  
  11.          Console.Writeln(“Testing method for the data”);  
  12.                  
  13.  }   
  14.   }  
  15. }  

That’s violate SOLID principle “Open Close” which says "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

So to avoid it same as make use of the abstraction i.e. create interface as which already done for to resolve tight coupling, so class extension can be done easily.

Below is how to extend the code that doesn’t break “Open Close” principle.

 

  1. Class DependencyClass : IDependencyClass  
  2. {  
  3.  public void Test()  
  4.   {  
  5.     Console.Writeln(“Testing method for the data”);  
  6.   }  
  7. }  
  8.   
  9. Class SecureDependencyClass : IDependencyClass  
  10. {  
  11.   IDependencyClass _b;   
  12.   public SecureDependencyClass(IDependencyClass b)  
  13.   {  
  14.     _b = b;  
  15.   }  
  16.   public void Test()  
  17.   {  
  18.     using(PrincipalContext pc = new PrincipalContext(ContextType.Domain,   
  19.         "YOURDOMAIN"))  
  20.  {  
  21.       bool isValid = pc.ValidateCredentials("myuser",   
  22.        "mypassword");  
  23.                if(isValid)  
  24.          this._b.Test();     
  25.                  
  26.  }   
  27.   }  
  28. }  

As you see in above code new class is created with the name SecureDependencyClass. This class extends the functionality of the previous class and also not breaks “Open Close” principle.

This is done by injecting exiting class DependencyClass in the new class SecureDependencyClass i.e that is also example of Dependency injection. So SecureDependencyClass consume dependency DependencyClass.

And which change consumer client code like as below

 

  1. Public class client  
  2. {  
  3.      Public static void main()  
  4.      {  
  5.         IDependencyClass dependency = new SecureDependencyClass(new   
  6.        DependencyClass());  
  7.         NeedDependencyClass a = new NeedDependencyClass(dependency);  
  8.       }  
  9. }  
  10.   
  11. public class NeedDependencyClass  
  12. {  
  13.   Private readonly IDependencyClass _b;  
  14.   public NeedDependencyClass(IDependencyClass b)  
  15.   {  
  16.      _b = b;  
  17.   }  
  18.   public void Test()  
  19.   {  
  20.      _b.Test();  
  21.   }  
  22. }  

Image below shows SecureDependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class SecureDependencyClass.

 

This also shows the NeedDependencyClass is not dependent on specific class but on the Abstraction.

4) Make class Testable

Now once the second step class NeedDependencyClass easily becomes testable. Because problem with original code is hardcode dependency that is not replaceable.

Example , following is the final code

  1. public class NeedDependencyClass  
  2. {  
  3.   Private readonly IB _b;  
  4.   public NeedDependencyClass(IB b)  
  5.   {  
  6.      _b = b;  
  7.   }  
  8.   public int Test()  
  9.   {  
  10.      var c=_b.Test();  
  11.      return c*10;  
  12.   }  
  13. }  
  14.   
  15. public class DependencyClass :IDependencyClass  
  16. {  
  17.   public void Test()  
  18.   {  
  19.     // code for getting value form database  
  20.     using(SqlConnection c = new SqlConnection(connectionstring))  
  21.     {  
  22.      c.open();   
  23.         SqlDataReader myReader = null;  
  24. SqlCommand    myCommand = new SqlCommand("select count(*) from table", c);  
  25.         return (Int32) cmd.ExecuteScalar();  
  26.   }  
  27. }  

As per the code Test method of the class DependencyClass does connection with sql server and return value.

But for testing of the class NeedDependencyClass there is no need to perform expensive database connection. So we replace class DependencyClass with the TestDependencyClass class like as below.

  1. public class NeedDependencyClass  
  2. {  
  3.   Private readonly IDependencyClass _b;  
  4.   public NeedDependencyClass(IDependencyClass b)  
  5.   {  
  6.      _b = b;  
  7.   }  
  8.   public int Test()  
  9.   {  
  10.      var c=_b.Test();  
  11.      return c*10;  
  12.   }  
  13. }  
  14.   
  15. public class TestDependencyClass :IDependencyClass  
  16. {  
  17.   public void Test()  
  18.   {  
  19.      return 10;  
  20.   }  
  21. }  
  22.   
  23. Public class TestClient  
  24. {  
  25.      Public static void main()  
  26.      {  
  27. NeedDependencyClass a = new NeedDependencyClass(new TestDependencyClass());  
  28.       }  
  29. }  

Conclusion

So Dependency injection is one of important design pattern which allows developing maintainable code which also satisfies SOLID principals. DI not only helpful in above this problem but we can also achieve below,   Other thing can be achievable by DI is

  1. Parallel programming of application
  2. Late Binding


Similar Articles