The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

Dependency Injection Design Pattern

Creational pattern. Creational design patterns are concerned with object creation.

The Dependency Injection design pattern solves problems like: How can a class be independent of how the objects it requires are created?

Open in the interactive referenceDownload the PDF reference

Problem

The Dependency Injection design pattern solves problems like:
How can a class be independent of how the objects it requires are created?
How can the way objects are created be specified in separate configuration files?
See Applicability section for all problems Dependency Injection can solve. See Solution section for how Dependency Injection solves the problems.

  • An inflexible way is to create objects (new ServiceA1(), new ServiceB1()) directly within the class (Client) that requires (uses) the objects.
  • This commits (couples) the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects can't be replaced with mock objects.
    Furthermore, a class often requires objects that have further de­pendencies, which in turn have de­pen­dencies, and so on, which results in having to create a complex object structure manually.
  • That's the kind of approach to avoid if we want that a class is independent of how its objects are created.
  • For example, designing reusable classes that require (depend on) other objects.
    A reusable class should avoid creating the objects it requires directly (and often it doesn't know at compile-time which class to instantiate) so that it can accept the objects it requires at run-time (from an injector object).
  • For example, supporting different configurations of an application.
    Instantiating concrete classes throughout an application should be avoided so that the way objects are created can be specified in separate (external) configuration files.

Solution

The Dependency Injection pattern describes a solution:
Define a separate Injector object that creates and injects the objects a class requires.
A class accepts the objects it requires from an Injector object
instead of creating the objects directly.
Describing the Dependency Injection design in more detail is the theme of the following sections. See Applicability section for all problems Dependency Injection can solve. [See also MFI]

  • The key idea in this pattern is to separate using objects from creating them.
    A class is no longer responsible for creating the objects it requires (uses).
    Instead, a separate injector object creates the objects and injects them into the class.

    This is also referred to as inversion of control, which is a common feature of frameworks (compare with Template Method).
  • Define a separate Injector object:
    • The way objects are created (that is, the mapping of interfaces to implementations) is specified in separate configuration files or objects (ServiceA -> ServiceA1, ServiceB -> ServiceB1).
    • To let the injector do its work, classes must provide a constructor (and/or setter methods) through which the objects can be passed in (injected).
  • A class (Client) accepts the objects it requires automatically at run-time.
    • A class can use objects solely through their interfaces (ServiceA,ServiceB) and doesn't have to care about how the objects are created.
    • This greatly simplifies classes and makes them easier to implement, change, test, and reuse.

Applicability

Design Problems

  • Creating Objects
    • How can a class be independent of how the objects it requires are created?
    • How can a class accept the objects it requires (from an injector object)
      instead of creating the objects directly?
  • Specifying Different Configurations
    • How can the way objects are created (the mapping of interfaces to implementations) be specified in separate configuration files or objects?
    • How can an application support different configurations?
  • Resolving Dependencies Recursively
    • How can the objects a class requires be created recursively?

Refactoring Problems

  • Inflexible Code
    • How can instantiating concrete classes throughout an application (compile-time implementation dependencies) be refactored?
    • How can object creation that is distributed across an application
      be centralized and externalized?

Testing Problems

  • Unit Testing
    • How can the objects a class requires be replaced with mock objects
      so that the class can be unit tested in isolation?

Structure

Static Class Structure

  • Client
    • Requires ServiceA and ServiceB objects.
    • Accepts the objects from the Injector.
    • Is independent of how the objects are created (which concrete classes are instantiated).
    • Doesn't know the Injector.
  • Injector
    • Creates the ServiceA1 and ServiceB1 objects; creates the Client (if it doesn't already exist) and injects the objects into the Client.

Dynamic Object Collaboration

  • In this sample scenario, an Injector object creates ServiceA1 and ServiceB1 objects. Thereafter, it creates a Client object and injects the ServiceA1 and ServiceB1 objects.
    Let's assume that the Injector uses a Configuration file that maps ServiceA and ServiceB interfaces to ServiceA1 and ServiceB1 implementations.
  • The Injector starts with creating the ServiceA1 and ServiceB1 objects.
  • Thereafter, the Injector creates the Client object and injects the ServiceA1 and ServiceB1 objects.
  • The Client object can then use the ServiceA1 and ServiceB1 objects as required.
  • See also Sample Code / Example1.

Not included on this page: Intent, Motivation, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.