IOC, DI, DIP

These three things are often confused - IOC, DIP and DI. I found a lot of blog posts on this topic trying to describe the difference between and most of them were a bit controversial so I decided to make some research so I could formalize and structure this knowledge. These questions are often used in interviews so knowing the difference is very important.

Inversion of Control Principle

Inversion of Control (IOC) is a design principle which recommends delegating any additional class responsibilities to other objects (i.e. control to other objects) to achieve less coupling.

Control over the flow (via callbacks for example) and control over the object creating and binding are the main responsibilities you may want to delegate from class.

So you could see, IOC is a very broad term. There are a lot of ways to implement inversion of control.

Dependency Injection Pattern

Dependency Injection (DI) is design pattern which can help with IOC. It allows to create dependent objects outside of a class and provide those objects to the class.

Let's say we have a client which depends on service. We add another object called injector which injects the service into the client. That's how DI works.

Injector can inject dependencies via client constructor, client methods and client properties. Those are three injection types.

Dependency Inversion Principle

Dependency Inversion Principle (DIP) is a design principle to achieve less coupling by following two rules in your code.

  1. High-level modules should not depend on low-level modules. Both should depend on the abstractions.
  2. Implementation details should depend on abstractions. Abstractions should not depend on details.

By the way, DIP is D from SOLID principles.

Basically DIP is something which stands out of first two. It's just a way to achieve less coupling on its own.

Conclusion