In software engineering, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. we can use dependency as an object.
It is a technique in which an object receives other objects that it depends on, called dependencies.The code that passes the service to the client is know as injector.It is a widely used design pattern that helps separate your components’ behaviour from dependency resolution.
Why we need?
DI achieves several goals:
- It allows you to easily bind different implementations for the same component. This is useful especially for testing, where you can manually instantiate components using mock dependencies or inject an alternate implementation.
- It allows you to avoid global static state. While static factories can achieve the first goal, you have to be careful to make sure your state is set up properly. In particular Play’s (now deprecated) static APIs require a running application, which makes testing less flexible. And having more than one instance available at a time makes it possible to run tests in parallel.
Three types of dependency injection:
Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
Property Injection: In the property injection (aka the Setter Injection), the injector supplies the dependency through a public property of the client class.
Method Injection: In this type of injection, the client class implements an interface which declares the method(s) to supply the dependency and the injector uses this interface to supply the dependency to the client class.
Advantages of DI
- Helps in Unit testing.
- decreased coupling between classes and their dependencies.
- Extending the application becomes easier
- programs become more reusable, testable and maintainable.
Disadvantage of DI
- Makes code difficult to trace because it separates behavior from construction.
- Encourage dependence on a framework.