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:
- namespace ConstructorInjection
- {
- class Program
- {
- static void Main(string[] args)
- {}
- }
- class A
- {
- B b;
- public A()
- {
- b = new B();
- }
- }
- class B
- {}
- }
Now with Constructor Injection,
- namespace ConstructorInjection
- {
- class Program
- {
- static void Main(string[] args)
- {
- A objA = new A(new B());
- }
- }
- class A
- {
- B b;
- public A(B objB)
- {
- this.b = objB;
- }
- }
- class B
- {}
- }
Now this will surely give you advantages.
- Control each and everything from main function.
- 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.