Dependency Inversion Principle (DIP)

This is the ‘D’ in SOLID, also see Dependency Injection Frameworks

Definition (Robert C. Martin and Micah Martin)

The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Furthermore, abstractions should not depend on details, but rather details should depend on abstractions. This is from the Agile Principles, Patterns, and Practices in C# book by Robert C. Martin and Micah Martin.

Definition (Mark Seemann)

“Dependency Injection is a set of software design principles and patterns that enable us to develop loosely coupled code.”

Inversion of Control

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC.
IOC is a concept where the flow of application is inverted. … DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means.

Inversion of Control of IoC can be implemented in two ways, one using a Service Locator and another is Dependency Injection.

Implementation - Dependency Injection

This is a Strategy Pattern. The most common implementation is constructor injection. Dependencies are passed in via the constructor. The constructor then is being honest with the things that call it in that it is explicitly stating the things that it needs in order for it to be in a valid state and to be able to do the work that it expects to be able to do.

  • Classes are self-document what they need
  • Works well with or without a container
  • Classes are always in a valid state once constructed.
  • Constructors can end up with many parameters/dependencies, which is a design smell.
  • Some features, EG, serialization, may require a default constructor.
  • Some methods in the class may not require things that other methods require, which is a design smell.

The dependencies can also be injected using:

Implementation - Service Locator

With the Service Locator, the class is still responsible for creating its dependencies. It just uses the service locator to do it. With DI, the class is given its dependencies.

References & Sample Code