Dependency injection

From CSSEMediaWiki
Revision as of 11:10, 16 October 2010 by Tanmay Bhola (Talk | contribs)
Jump to: navigation, search

In the Dependency Injection pattern, an object's dependencies are provided externally. This separates behaviour from dependency resolution. It is the general concept behind the Factory patterns, which aim to reduce coupling and add unwanted dependencies.

It can also be viewed as an example of the Dependency inversion principle, because it removes dependencies from low-level concepts in favour of the higher-level abstractions.

Contents

Participants

This design pattern can arise in a few different forms, but there are generally three participants.

  • Dependent: An object that is expected to perform some task
  • Dependencies: The object(s) that the dependent relies on to perform some task
  • Injector: Composes the dependent with its dependencies so it is ready to use

The injector (also known as a provider or container) handles all issues associated with composing these objects and managing them throughout their life cycle. This includes when and how they are instantiated and disposed of. The injector can be implemented as a abstract factory or service locator.

Three examples of managing dependencies

A dependency hard coded into an object:

class SimpleCar implements Car {
   private Engine engine = new SimpleEngine(); // Note the dependency on the SimpleEngine implementation

   public accelerate() {
       engine.setFuelValveIntake(gasPedalPressure);
   }
}
   

Dependency injection through the constructor:

class SimpleCar implements Car {
   private Engine engine;
   public SimpleCar(Engine engineImpl) {
       engine = engineImpl;
   }
   public void accelerate() {
       engine.setFuelValveIntake(gasPedalPressure);
   }
}

Martin Fowler described three types of dependency injection: interface, setter and constructor injection. Each method provides a slightly different way of "injecting" the dependency into a class without using hard-coded references.

There are also frameworks in most major languages for dependency injection. These frameworks let dependencies be defined with additional language syntax so that the framework can manage the dependencies - for example, an XML configuration file may be used to define what implementations should be used for each abstraction.


See also

References

Personal tools