Thursday, October 3, 2013

Dependency Injection - An Introduction

Dependency

Dependency is when a class needs instances of another class to function correctly.
Following is an example of dependency:
    class X
    {
        ...
        Y obj = new Y("xyz", "abc") ;
        ...
    }

Dependency Problems

  • Dependencies are hardcoded.
  • Unit testing becomes difficult as well, where we need to mock the depencies to perform isolated test cases.
  • With dependencies like above, if different implementation of Y (with same interface) is needed. Actual code needs to be changed.
  • Also the code here is not based on interface so its even further less flexible.
  • If dependency class has further dependencies, those will be needed as well.

Dependency Injection

  • Injecting Dependency from (pushed from) outside into a class at runtime.
  • Dependent object instead of instantiating dependencies using "new" operator from inside of the class should take dependent object via constructor parameters or setters.
  • It decouples class's construction from the construction of its dependencies.
  • Code should depend upon abstractions(interfaces) rathen than implementation(class references).
  • Dependency Injection is for Loose Coupling.
    • An object's dependencies should be on interfaces and not on "concrete" objects.
    • Dependencies should be less.
    • Loose coupling promotes greater reusability, easier maintainability.

    class X
    {
        InterfaceY objY = null;
        ...
        X (InterfaceY dependencyObj)
        {
            objY = dependencyObj ;
         }
        ...
    }

  • Software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time
  • Its a configuration style of prorgamming, object is configured from outside (may be a configuration file) rather than inside.

Primary ways to implement Dependency Injection:

  • Constructor Injection
    • These are considered better than others since at the time of the creation of the class you know what is needed to perform its job.
    • Easier to maintain.
  • Setter Injection
  • Method Injection

How to manage and instantiates dependencies?

  • Each of our classes require dependencies, we need to figure what dependency each class needs and how to instantiate the dependencies.
  • The answer is Dependency Injection container.
  • Dependency Injection container contains map of dedencies needed by a class with the logic to create instances of those dependencies if needed.

Related Topics:
Dependency Inversion Principle
Inversion control Principle
Inversion of Control Container
Dependency Lookup
DI Container Implementations
Butterfly container
factory vs container
factory pattern vs DI Container

No comments:

Post a Comment