Dependency injection or DI is one of the important concepts in computer programming. It refers to the process of supplying an external dependency to a software component. Let’s try to understand the concept of Dependency Injection. There is a consumer who needs a particular service to accomplish a certain task. Without dependency injection, the consumer would be responsible for handling complete life-cycle of that service. Life cycle means instantiating, opening and closing streams etc of that service.
But if you use the concept of dependency injection, the life-cycle of a service is handled by a dependency provider which is in normal case a web container rather than the consumer. The consumer would thus only need a reference to an implementation of the service that it needed in order to accomplish the necessary task.
In Dependency injection, there are three elements: a dependent, its dependencies and an injector also known as provider or container. The dependent is a consumer that needs to accomplish a task in a computer program. In order to do so, it needs the help of various services (which are called dependencies) that execute certain sub-tasks. The provider is the component that is able to compose the dependent and its dependencies so that they are ready to be used, while also managing these objects’ life-cycles. In other words, dependency injection decouples high-level modules from low-level services.
This injector can be implemented as
- a service locator
- an abstract factory
- a factory method
- with the help of frameworks like Spring IOC.
We have one small example. A car (the consumer) depends upon an engine (the dependency) in order to move. The car’s engine is made by an automaker (the dependency provider). The car does not know how to install an engine into itself, but it needs an engine in order to move. The automaker installs an engine into the car and the car utilizes the engine to move.