Dependency Injection, also called IoC - Invertion of Control, originated from Martin Fowler's famous article Inversion of Control Containers and the Dependency Injection pattern. Basically the idea is "let the outside caller provide the desired implementation."
For example, when accessing a service, instead of holding a reference to that service, a software component provide a property that can hold that type of reference, when the object is created, a service implementation reference is automatically injected into the property.
Here is an example with factory pattern:
public class DAOFactory
{
public static T Create<T>()
{
IDatabase db = Registry.Fetch<IDatabase>();
T dao = Registry.Fetch<T>();
dao.Database = db;
return dao;
}
}
ICustomerDAO dao = DAOFactory.Create<ICustomerDAO>();
when dao is created, the Database reference is automatically injected by the factory method, rather then with code by dao itself.
Why IOC? one good reason is that IOC gives more power for decoupling componments, as a result, unit test is a lot easier. Actually, there are already dependency injection frameworks out there to provide mock components to facilitate unit test.
Based on Martin Fowler, there are three types of injection: Constructor, Setter and interface. Injection can also be defined with configure file, that gives more flexibility to assemble an application.
SOA - service oriented architecture, ervice - a set of business or functionalities. In SOA development, usually use configure mechanism for deciding which implementation gets injected into an object.
It is kind of implementation of ObserverFactory pattern.
No comments:
Post a Comment