DEV Community

Discussion on: What is Dependency Injection?

Collapse
 
simoroshka profile image
Anna Simoroshka

Nice! Could you also explain inversion of control in simple words, please?

Collapse
 
setagana profile image
setagana

I'm not the original poster, but I'll take a stab at it:

The technique of dependency injection has a side effect of introducing the philosophy of inversion of control to your application. The philosophy of inversion of control is all about where decisions happen in your application, and IoC states that they should happen at a higher level of the application or in a point of central authority.

Say you have a logging class in an application where there is no inversion of control. Somewhere else in your application some logic determines that it's necessary to log something and calls your logging class informing it of the log level and the message to log.

Maybe your logging class has some internal logic which states that if the log level is Fatal; it's not only going to log to console, it's also going to send an email. In this situation there's no inversion of control. The decision (which is what IoC is all about) happens at a deep level of your application - inside the logging class which is called by something else.

When you decide to refactor your logging class for inversion of control in this situation, you start by saying I want to make the decision of whether or not to email at a higher point in my application than where it is now. One technique to use to achieve that goal is dependency injection - you could inject a communication strategy into your logging class when you make the call to log. Now your logging class doesn't make any decisions itself - it just interacts with the communication strategy that is injected without caring about the details inside it.

Dependency injection is probably the most widely known and widely used technique to introduce Inversion of Control, but there are others such as the service locator pattern. In this pattern your logging class is only aware of a single service locator for communication. It calls that service locator and passes on the same information every time, and the service locator decides which communication service to pass that information on to. The decision of communication strategy no longer sits in your logging class, but you're also not injecting any dependencies into the logging class.