M. Fowler. Inversion of Control Containers and the Dependency Injection Pattern. 2004.

Fowler's example implemented in C++ using GoogleFruit can be found on GitHub.

Dependency injection describes a pattern applying the concept of inversion of control to lookup plugin implementations (or specifically, interface implementations). In the course of the article, Fowler describes the three different types of dependency injection:

  • (Type 1) Interface injection.
  • (Type 2) Setter injection.
  • (Type 3) Constructor injection.

The example used for illustration is shown in Figure 1. A movie finder allows a user to query movies according to different criteria. As movie source, the movie finder uses a movie lister which returns a list of available movies. In this scenario, the movie finder explicitly instantiates the underlying movie lister. With dependency injection, we want to avoid this explicit dependency, by "injecting" the movie lister implementation into the movie finder. For this task, a dependency injection framework may be used. The framework acts as "assembler", knowing the concrete implementation to use as well as the component to inject it into. The class diagram of Figure 1 changes to the one in Figure 2.


Figure 1: Simple class diagram illustrating the situation without dependency injection. The movie finder explicitly needs to instantiate the movie finder implementation to use. Instead, we would prefer to "inject" the concrete movie finder implementation to the movie lister.


Figure 2: Simple class diagram illustrating the situation with dependency injection. The movie lister expects the concrete movie finder as constructor argument. The "assembler" is told which implementation to use and injects it into the constructor.

What is your opinion on this article? Let me know your thoughts on Twitter @davidstutz92 or LinkedIn in/davidstutz92.