Dependency Injection (DI) is a programming technique that makes a class independent from its dependencies. This article describes a quick overview of dependency injection: what is it, and when to use it. Summer of the article:
- What is Dependency Injection?
- Why we need Dependency Injection?
- Dependency Injection Framework
What is Dependency Injection?Dependency or dependent means relying on something for work. For example, we can say, our daily life is relying too much on smartphones. That means we are dependent on smartphones.
In a programming language, when class A uses some functionality of class B, then we can say class A has a dependency of class B. In C# language, if we want to use a method of other classes, at first we need to create the object of that class. For the above example, class A needs to create an instance of class B.
In short we can say, transferring the task of creating the object to someone else and directly using the dependency is call dependency injection or DI. DI is one of the possible implementations of the Dependency Inversion Principle (DIP), which is the fifth principal of SOLID.
Types of DI
- Constructor injection
- Property injection
- Method injection
Benefits of DI
- It helps to enable loose coupling, which is very important in software programming.
- It is complex to learn. And overused can lead to management issues and other problems.
Disadvantages of DI
- Some compile time errors may occurred in run-time.
- It helps in unit testing.
Dependency Injection FrameworkWe can implement DI in our own style or can use third party libraries or frameworks. Some libraries or frameworks that implement DI is given bellow:
- Sprint (Java)
- Castle Windsor (.Net)
- Google Guice (java)
- Unity (.Net)
- Managed Extensibility Framework (MEF)
- Simple Injector
- Structure Map
- Microsoft.Extensions.DependencyInjection (.Net)