What is Dependency Injection?
I recently encountered Dependency Injection and I found it quite confusing at first. I’ll try to break it down for you so you won’t have to struggle like I did at first.
In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. In the typical “using” relationship the receiving object is called a client and the passed (that is, “injected”) object is called a service.
This is how Wikipedia has defined Dependency injection. However, as a new software engineer/recent computer science graduate — this didn’t make any sense to me.
Before, I discuss the fundamentals of Dependency Injection (DI), I’ll deep dive into the concepts behind Inversion of Control (IoC). IoC is one of the core foundations of software engineering. Essentially, it shifts the responsibility of controlling/managing objects to a container.
So, what is Dependency Injection?
Dependency injection is a design pattern used to actually integrate IoC into your code. Essentially, the dependencies of your class are injected into the class via the constructor.
Imagine you had a Laptop class, which depends on a HardDrive class, Ram class etc. Instead of calling the dependencies in the Laptop class using the new keyword — we can make use of Inversion of Control and let our containers manage all that for us.
Why do I need Dependency Injection?
Well, essentially if we used the former approach and instantiated the dependencies ourselves, then we would be hard-coding. And, this is a very bad thing. The moment we use the ‘new’ keyword we are essentially tight coupling our code. This reduces the reusability of our code, makes it less scalable and can cause problems later on due to the lack of flexibility this approach provides. Whereas, using Dependency Injection allows containers to carry the responsibility of injecting our dependencies, managing our objects via Inversion of Control hence making our code loosely coupled. There are a range of other benefits i.e. improves testability of code, enhances reusability, increases readability of code etc.
This was a short, high level overview of what dependency injection is. Basically, instead of creating your own dependencies, inject them. If you need to access a class or object in a different class — inject it using Dependency Injection. Do not create your own. Shift that responsibility onto the ApplicationContext (if you’re using Java Spring Boot for example). This will manage the objects of your application and it will use Dependency Injection to achieve Inversion of Control