Dependency Injection (plus Inversion of Control, and Dependency Inversion principle)

This is a note for myself to get to know more concrete details about Dependency Injection.

Dependency injection is a design pattern or at least “a set of patterns and principles; i.e. not a single pattern”. The intent behind dependency injection is to achieve separation of concerns of construction and use of objects.

This Wikipedia section is excellent in defining roles in dependency injection (their examples are great too):

  • the service objects, which contain useful functionality
  • the interfaces by which those services are known to other parts of the code
  • the client object, whose behavior depends on the services it uses
  • the injector, which constructs the services and injects them into the client

Three different types of depedency injections:

  • Constructor injection
  • Setter injection
  • Interface injection

Some thoughts from Martin Fowler:

  • Generally, Dependency Injection is better than Service Locator.
  • The choice between them is less important than the principle of separating configuration from use.
  • Prefer constructor injection over setter injection.

References:

One thought on “Dependency Injection (plus Inversion of Control, and Dependency Inversion principle)

Leave a comment