Severin Perez

Reference: Dependency Injection vs Dependency Inversion

October 04, 2018

Although related, dependency inversion and dependency injection are two distinct concepts. We can define each of them, as well as their relationship with one another, as follows:

  • Dependency Injection: A mechanism in object-oriented design that uses setters, constructors, or interfaces to “inject” a dependency into a given object. In using this mechanism, a given object (the client) ceases to be responsible for the instantiation of its own dependencies (its services). The client is thus unaware of the implementation of its services and only knows abstractly that it needs some kind of service to operate. The aforementioned injection mechanisms are then used to provide the client with any necessary services. The advantage of this mechanism is a decrease in coupling between client and service, thus increasing flexibility in that new and different services can be created and injected as needed.
  • Dependency Inversion: A structural pattern in object-oriented design wherein high- and low-level modules depend on mutual abstractions rather than directly on one another. Use of this pattern effectively “inverts” traditional dependency hierarchies. The intermediary abstractions, typically interfaces, are used as contracts that define the parameters of a given module’s expected behavior. The advantage of dependency inversion is that it prevents changes in lower-level modules from affecting the functionality of higher-level modules, thus increasing flexibility, mobility, and maintainability.
  • Inversion through Injection: If dependency inversion is a structural pattern used to design flexible systems, then dependency injection is a mechanism used to implement that structure. In dependency inversion, high- and low-level modules use interfaces to interact with one another. These interfaces may be understood as injectors that are used by a high-level client module to take advantage of a low-level service module. In practice, the particular service will be instantiated from outside of the client class and then provided to the client through a constructor or setter.

References


You might enjoy...


© Severin Perez, 2020