One may think that
Inversion of Control and
Dependency Injection are the same concept. But it is not.
Let’s use a real-world example to explain this better. A car needs wheels to operate. Without one or more wheels, the car has no use. So we can safely assume that the wheels are dependencies of car.
Likewise, In programming, One module may require another module for its actions. Without the other, the first may not be able to perform its task. These are called dependencies.
Imagine if the manufacturer fused all wheels to the car’s shaft. It will be hard to replace the tires when we need to upgrade or swap a flat tire. In this case, you have two options. Buy a new car or fix the car by breaking and rewelding the wheel.
We know why this is a bad idea. But buying a new car is expensive. And breaking apart and welding the wheels is going to cost energy.
Similarly, if we build out modules too dependent on each other, then it will be hard to refactor. That is why we need DI. Dependency injection helps achieve Inversion of control. That means applications are easy to refactor.
You can implement Dependency Injection in various ways. For any object-oriented programming language, you can inject dependencies in the following methods.
- Uses getters and setters to supply objects to the parent object.
- very simple to implement.
- Uses constructors while instantiating the object.
- Usually done with the help of
Java reflections API.
- Injects objects just for specific method calls.
- Best way to implement this way is to use
Given the nature of these implementations and extra technical debt involved, You should ideally use a framework that provides DI. This way, You can concentrate on the business logic.
Some of the popular DI frameworks in Java are,
You should note that
Dependency injectionis not just for Object oriented Programming languages. For example, You can inject
method referencesto a functional programming modules.