Understanding the Concept of "Inversion Of Control" and "Dependencies Injection" - duongphuhiep/blog1 GitHub Wiki

Many veterant developers (including myself) often confuse, mix / merge together the concept of "Inversion Of Control" (IoC) and "Dependencies Injection" (DI). As they are often used interchangeably but have distinct meanings.

Inversion of Control (IoC)

Inversion of Control is a programming principle that essentially means delegating the responsibility of creating and managing objects from the client code (the caller) to a third-party mechanism (such as a third-party framework or an external container).

  • Traditional approach: In traditional programming, the client code is responsible for creating and managing the objects it needs. This means the client code has direct control over the object's lifecycle.
  • IoC approach: With IoC, this control is "inverted" or more accurately is "delegated". Instead of the client code being in charge, a framework or container takes over the responsibility. The client code simply requests the objects it needs, and the container provides them.

While technically the flow of control is inverted: the caller becomes the callee (don't call us, we will call you), it is helpful to think of it as Delegating the responsibility of managing dependencies to an external component or Framework.

Dependency Injection (DI) is only a specific implementation of the IoC principle

Besides DI, there are a few other common ways to implement IoC:

  • Service Locator: A pattern where objects request their dependencies from a central registry.
  • Factory Pattern: In the factory pattern, object creation is delegated to a separate factory class. This way, the class doesn’t control how its dependencies are created, achieving IoC.
  • DI provides dependencies (objects or services) to a class from an external source, typically through constructor injection, property injection, or method injection.

what a DI framework usually offers?

  • a way to declare or to register object (or the object creation) to a Dependency graph.
  • a Container
  • a Resolver