(life => life.make_it_better)

Introduction to Dependency Injection

What is Dependency Injection?

In simple words, Dependency Injection (DI), is a type of IoC where the creation and binding of a dependency is moved outside of the class that depends on it.

Say suppose when you pack your lunch, you know what you have packed inside it. But when you know that the food will be provided, you know that you need not to worry about lunch, it will just be served when you need it.

Similar to above example, when you don’t use DI, your class will have the creation and binding of dependencies inside it. But when you use DI, your class will just work taking into consideration that the required dependencies will be provided by a service.

Where do dependencies come from?

For example, in your class MyClass, you have a dependency on say class Dependency. Let us assume that MyClass directly depends on Dependency. Now, to follow DIP, we create an interface IDependency that Dependency implements. So our class now looks like this:

Even after creating an interface, MyClass still creates an object of class Dependency inside it and it means it is controlling the the creation of it.

So we can introduce an Injector which will take care of the issue above and it will have knowledge of MyClass & IDependency. Using this Injector, we can make MyClass have no knowledge about Dependency class.

Types of Dependency Injection

Constructor Injection

is very common and simple.

pass the dependency into dependent class via constructor of the class.