CodePark/ questions / Dependency injection & inversion
START PRACTICINGPRACTICE
Backend question · Software design & patterns › Dependency injection & inversion

What is the difference between Dependency Inversion, Dependency Injection and Inversion of Control, and where does an IoC container fit?

Dependency Inversion is a principle, Inversion of Control is a general idea, Dependency Injection is a technique, and an IoC container is a tool.

Dependency Inversion (DIP) is a design principle. It is the D in SOLID. High-level policy and low-level details both depend on abstractions, such as interfaces. The high-level side owns the abstraction.

Inversion of Control (IoC) is a broader idea. A framework or caller controls the flow and calls your code. Your code does not call the library. For example, Express calling your route handler is IoC.

Dependency Injection (DI) is a technique. It is one form of IoC, applied to creating objects. An object receives its dependencies from outside, usually through its constructor. It does not create them or look them up itself.

An IoC container is a tool that automates DI. It builds the object graph for you. Examples are Nest's injector and InversifyJS.

Two things to remember:

  • You can do DI by hand, without a container.
  • You can use DI without DIP, if you inject concrete classes.
  • DIP is a principle about the direction of dependencies.
  • IoC is the general idea that the framework calls your code.
  • DI is a technique where dependencies are supplied from outside.
  • A container is a tool that automates DI, but DI also works without one.