This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. |
You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Figure 1 illustrates this.
Figure 1 ClassA has dependencies on ServiceA and ServiceB
This situation has the following problems:
Any of the following conditions justifies using the solution described in this pattern:
Delegate the function of selecting a concrete implementation type for the classes' dependencies to an external component or source.
The Inversion of Control pattern can be implemented in several ways. The Dependency Injection pattern and the Service Locator pattern are specialized versions of this pattern that delineate different implementations. Figure 2 illustrates the conceptual view of both patterns.
Figure2 Conceptual view of the Service Locator and Dependency Injection patterns
For more information about these patterns, see Dependency Injection and Service Locator.
The following are example implementations of the Inversion of Control pattern:
C#
public class ModuleA : IModule{ private readonly IRegionManager _regionManager; public ModuleA(IRegionManager regionManager) { _regionManager = regionManager; } ...}
Because the ModuleA class is instantiated by a container and an instance of the region manager service is registered with the container, the ModuleA class receives a valid instance of the region manager service when it is constructed. Note that a mock instance of the region manager service can be supplied when testing the ModuleA class by passing the mock instance in the constructor's parameter.
C#
public void Initialize(){ RegisterViewsAndServices(); INewsController controller = _container.Resolve<INewsController>(); controller.Run();}
Note that for testing purposes, you could configure the container to return a mock instance that implements the INewsController interface instead of the real implementation. This enables you to test the NewsModule class in isolation. The following code, extracted from the NewsModuleFixture test class (located in StockTraderRI.Modules.News.Tests\NewsModuleFixture.cs), shows how the NewsModule class can be tested in isolation using a mock instance for the INewsController interface.
C#
[TestMethod]public void InitCallsRunOnNewsController(){ MockUnityResolver container = new MockUnityResolver(); var controller = new MockNewsController(); container.Bag.Add(typeof(INewsController), controller); var newsModule = new NewsModule(container); newsModule.Initialize(); Assert.IsTrue(controller.RunCalled);}
The Inversion of Control pattern has the following liabilities:
The following patterns are related to the Inversion of Control pattern: