Thursday, August 1, 2013

Dependency Injection

Dependency Injection removes hard-coded dependencies and makes it possible to change them at run time or compile time.


Dependency NON Injection
Following class has a dependency named “serviceA” and it initialized in constructor. There is no dependency injection here.



Dependency Injection
Constructor has change to inject “serviceA  dependency in to class.



The following are the two main forms of dependency injection:

Constructor Injection
In constructor injection, you use parameters of the object's constructor method to express dependencies and to have the builder inject it with its dependencies.

Setter Injection
In setter injection, the dependencies are expressed through setter properties that the builder uses to pass the dependencies to it during object initialization.

Example
Service Interface and implemented classes

ServiceConnector class with Dependency Injection

Connect with ServiceA and ServiceB