Why is DI necessary?
- Remove codes of initiating dependencies in your application
- Helpful for Unit Test
How does DI remove codes of initiating dependencies?
Control functionality from a central place
Control dependency functionality from a central place instead of spreading it throughout the program
// Instead of this code public class A { private Dependency depend; public A() { this.depend = new Dependency(); // A *depends on* Dependency } public void DoSomeStuff() { // Do something with Dependency here } } public static void Main(string[] args) { A a = new A(); a.DoSomeStuff(); }
// Dependency can be injected from one central place public class A { private Dependency depend; public A(Dependency dependent) { // A now takes its dependencies as arguments this.depend = dependent; } public void DoSomeStuff() { // Do something with Dependency here } } public static void Main(string[] args) { Dependency dependent = new Dependency(); // Dependency is constructed here instead A a = new A(dependent); a.DoSomeStuff(); }
How is DI helpful for Unit Test?
Dependency injection is a way to create your dependencies outside of the class that uses it. You inject them from the outside, and take control about their creation away from the inside of your class. It’s helpful to mock your dependencies in order to test your Classes
Leave a Reply