A Custom IoC Container and DI Framework

,

The custom Dependency class is a static class used to associate types or resolve instances of types at runtime. The Dependency class serves as a proxy to an instance of IoC container, allowing you to change the underlying IoC container implementation. It does this by leveraging the Microsoft.Practices.ServiceLocation API, which provides a container agnostic type resolution mechanism. The Dependency class also uses a custom IDependencyRegistrar to create type associations, something notably absent from the Microsoft.Practices.ServiceLocation API.

To use the Dependency class, an IoC container implementation must be specified.

Initialization of the IoC infrastructure should be performed as soon as possible before the app displays its UI. This helps prevent type resolution failures.

In the sample, located in the WPUnleashed.Examples project, the container initialization code is placed in the App class, as shown in the following excerpt:

void InitializeContainer()
{
    SimpleContainer container = new SimpleContainer();
    container.InitializeServiceLocator();

#if DEBUG
    Dependency.Register<ILicensingService>(new MockLicensingService
    {
        IsTrial = true
    });
    Dependency.Register<IMarketplaceDetailTaskAdapter>(
        new MockMarketplaceDetailTaskAdapter(
            () => Debug.WriteLine("Launching Marketplace Detail...")));
#else
    Dependency.Register<ILicensingService, LicensingService>();
    Dependency.Register<IMarketplaceDetailTaskAdapter,
                        MarketplaceDetailTaskAdapter>();
#endif
}

After the container is initialized, the Dependency class is used to register type associations. Creating a different set of type associations, depending on the build configuration, can be achieved using preprocessor directives. When using a DEBUG build configuration, mock implementations of the ILicensingService interface and the IMarketplaceDetailTaskAdapter interface are used. These types wrap and substitute the functionality provided by the built-in MarketDetailTask and LicenseInformation classes.


Tip

Rather than duplicating your type mappings across test and core projects, you may choose instead to create a dedicated class that includes type associations for each scenario you are covering: test, release, trial, and so on.



Note

This chapter demonstrates the use of manual mocking techniques and does not cover dynamic mocking using frameworks such as Moq. If you are not already familiar with mocking, I recommend exploring dynamic mocking because it offers advantages over manual mocking and can reduce the amount code that you need to write.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.7.154