Design Patterns interview question · Most asked

What is the difference between dependency inversion, dependency injection and inversion of control?

Summary

Dependency inversion is a design principle (high-level code depends on abstractions it owns). Dependency injection is a technique for supplying dependencies from outside (usually through the constructor). Inversion of control is the broader idea that a framework or container calls your code and manages wiring, instead of your code controlling everything.

Longer Answer

  • DIP (the D in SOLID): OrderService depends on an OrderStore interface, not on MySqlOrderStore.
  • DI: OrderService(store) receives its store; a composition root or container creates the real one.
  • IoC: "don't call us, we'll call you"; frameworks call your controllers, event handlers and lifecycle hooks. DI containers are one form of IoC.

You can apply DIP and DI with plain constructors and no framework at all.

Key Points

  • DIP: principle about the direction of dependencies.
  • DI: technique for passing dependencies in.
  • IoC: framework controls the flow and wiring.
  • DI doesn't require a container.

Deep dive: Design Patterns, Explained Simply: Dependency Injection Without a Framework

Explanation

What interviewers look for

Clear separation of principle, technique and broader concept.

Follow-up questions

  • What is a composition root?
  • Why is a service locator not the same as DI?

More most-asked Design Patterns questions

← All Design Patterns questions