2 min read

What is Dependency Injection (DI)?

August 20, 2020

One may think that Inversion of Control and Dependency Injection are the same concept. But it is not.

What are dependencies?

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.

Why we need it?

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.

How to implement DI?

You can implement Dependency Injection in various ways. For any object-oriented programming language, you can inject dependencies in the following methods.

  • Property Injection

    • Uses getters and setters to supply objects to the parent object.
    • very simple to implement.
  • Constructor Injection

    • Uses constructors while instantiating the object.
    • Usually done with the help of Java reflections API.
  • Method Injection

    • Injects objects just for specific method calls.
    • Best way to implement this way is to use reflections along with Proxy objects.

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,

  • Spring framework.
  • Play framework.
  • Guice.
  • Weld-CDI.

You should note that Dependency injection is not just for Object oriented Programming languages. For example, You can inject method references to a functional programming modules.