How is Inversion of Control related to Dependency Inversion

dependency-inversiondesign-patternsinversion-of-control

In many articles all over the web the terms Inversion of Control and Dependency Inversion Principle seem to be mixed up and used as synonyms (further confusion is enforced by the tools that are called "DI-Containers" and "IoC-Containers"). A Wikipedia article does a nice job trying to explain that IoC is not the same as DI:

inversion of control (IoC) describes a design in which custom-written
portions of a computer program receive the flow of control from a
generic, reusable library

So DIP is about having your modules depend on abstractions rather than concrete
implementations.

And IoC is about giving control over your program flow to a separate module. And one of the things you can have this module do is resolve the dependencies at runtime.

This difference does seem fair, but I've never seen anyone mention any other applications of the IoC principle other than dependency resolving. The Wikipedia definition is quite broad, and it seems like you could do so much more with a module that has that can make calls into your custom code based on its configuration and some internal logic.

So, here are some questions that I can't quite figure out yet:

  • What is the actual relation between IoC and DIP? Does IoC always serve as the means of implementing DIP?
  • Why are tools for dependency resolving called both DI- and IoC-containers? This implies that DI and IoC are the same thing.

Note: This question is not a duplicate of What is the difference between DI and IoC, because the latter asks about Dependency Injection, not Dependency Inversion.

Best Answer

There is a great article on Martin Fowler's site that has a chapter specifically about the difference between DIP, DI and IoC. The gist of it (as copied from that site) is

DI is about how one object acquires a dependency. When a dependency is provided externally, then the system is using DI. IoC is about who initiates the call. If your code initiates a call, it is not IoC, if the container/system/library calls back into code that you provided it, is it IoC.

DIP, on the other hand, is about the level of the abstraction in the messages sent from your code to the thing it is calling. To be sure, using DI or IoC with DIP tends to be more expressive, powerful and domain-aligned, but they are about different dimensions, or forces, in an overall problem. DI is about wiring, IoC is about direction, and DIP is about shape.

Related Topic