Inversion of Control
The following article is mainly from Prism documentation, it's just a review of IoC.
Having class depends on services or components whose concrete type is specified at the design time introduced several problems:
1. Update the dependencies need change the class who depends on them
2. Concrete dependencies must be available at compile time in order to build your type.
3. Hard to test, couldn’t use Mock or Stubs.
4. Manage the dependencies is a nightmare.
Solution: Your class does not create other objects on which they rely to do their work. Instead, they get these objects that they need from outside source.
Implementation Details:
The IoC pattern can be implemented in several ways. The Dependency Injection (DI) and the Service Locator patter (also known as IoC container) are two common ways.
1. Dependency Injection: a specialization of the IoC, uses a builder object to initialize object and provide the required dependencies to the object. There are two main form of dependency injection:
· Constructor injection: use parameters of the objects constructor method to express dependencies and to have the builder inject it with its dependencies.
· Setter injection: the dependencies are expressed through setter properties.
2. Service Locator: create a service locator that contains the dependencies and the service locator encapsulates the logic to locate them. In your class, use the service locator to obtain service instances.
Note: the service locator does not instantiate the services. It provides to way to register services and it holds references to the services. Once the service is registered, the locator can find the service. The service locator should provide a way to locate a service without specifying the concrete type.
Sample Code:
{
T Resolve<T>();
}
public class SimpleContainer : IIoCContainer
{
readonly Dictionary<Type, object> _container = new Dictionary<Type, object>();
public T Resolve<T>()
{
return (T)_container[typeof(T)];
}
public void Register<T>(object obj)
{
if (obj is T == false)
{
throw new InvalidOperationException("Invalid operation");
}
_container.Add(typeof(T), obj);
}
}
For the more complex container, refer to:
1. Unity Application Block: http://www.codeplex.com/unity/
2. Windsor Container: http://www.castleproject.org/container/index.html