The 3 Types of Dependency Injection
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have or which has expired. What you should be doing is stating a need, “I need something to drink with lunch”, and then we will make sure you have something when you sit down to eat.
John Munsch, 28 October 2009
John Munsch demonstrated how to explain Dependency Injection to a 5 year old kid on a Stack Overflow answer.
There are 3 types of Dependency Injections and here they are from the most to the least favorable order: Constructor Injection, Setter Injection and Property Injection.
Let’s assume a service implementation like below. We would like to inject that service to a controller.
Constructor Injection Example:
Setter Injection Example:
Property Injection Example:
As you can see in the all three implementations, none of them has a new instance of the service class. Now the client or framework will deal with creating a new instance of the service. And this is simply called Inversion of Control.
Dependency Injection (DI) is a design pattern used to implement Inversion of Control (IoC) which is a design principle.