Dependency Injection in C#

Went through various blog to get the better understanding of DI and finally sharing below what actually my understanding is:

Need to very careful when we have to design the solution. Keep the solution loosely coupled as much as you can .DI is more flexible as we have alternate solution to achieve the same.

Let say you have a class and it’s dependent on various components it can be other classes, services etc.

This situation may lead you in trouble like,

Your classes are difficult to test in isolation because they have a direct reference to their dependencies. This means that these dependencies cannot be replaced with stubs or mocks.

Look at the Code Snippet below:

  1. namespace ConstructorInjection  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {}  
  7.     }  
  8.     class A  
  9.     {  
  10.         B b;  
  11.         public A()  
  12.         {  
  13.             b = new B(); // A depends on B  
  14.         }  
  15.     }  
  16.     class B  
  17.     {}  
  18. }  
Now with Constructor Injection,
  1. namespace ConstructorInjection  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             A objA = new A(new B());  
  8.         }  
  9.     }  
  10.     class A  
  11.     {  
  12.         B b;  
  13.         public A(B objB) // A now takes its dependencies as arguments  
  14.             {  
  15.                 this.b = objB;  
  16.             }  
  17.     }  
  18.     class B  
  19.     {}  
  20. }  
Now this will surely give you advantages.
  1. Control each and everything from main function.
  2. Easily test each class in isolation.
The drawback, of course, is that you now have one mega-function that knows about all the classes used by your program. That's what DI frameworks can help with.