Sunday, August 31, 2014

Three steps to wire up your IOC container.

How can you dynamically and flexibly wire up your inversion of control container? Here are three easy steps to consider:

  1. Reflection
  2. Explicit
  3. Configuration

First, use reflection to help wire up your boiler plate or dynamic dependencies. Second, explicitly register and customize any additional dependencies that your application needs Third, use configuration last to dynamically override any of your previous settings, allowing you to make changes to your application in a live environment without having to rebuild or deploy.

Sample Code

Microsoft's Unity offers a last in win container, so if you follow the steps above in order you will have a very flexible configuration for your container!

public class UnityContainerFactory
{
    public static IUnityContainer CreateContainer(bool useConfiguration = true)
    {
        var container = new UnityContainer();
 
        // Step 1) Reflection
        var reflectionMap = GetTypesFromReflection();
        foreach (var pair in reflectionMap)
                container.RegisterType(pair.Key, pair.Value);
 
        // Step 2) Explicit
        container.RegisterType<IDemoService, StandardDemoService>();
 
        // Step 3) Configuration
        if (useConfiguration)
            container.LoadConfiguration();
 
        return container;
    }
 
    public static IDictionary<Type, Type> GetTypesFromReflection()
    {
        // TODO: Make this use reflection.
        return new Dictionary<Type, Type>
        {
            { typeof(IDemoService), typeof(SimpleDemoService) }
        };
    }
} 
 
public interface IDemoService { }
 
public class SimpleDemoService : IDemoService { }
 
public class StandardDemoService : IDemoService { }
 
public class AlternativeDemoService : IDemoService { }

Sample Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="ThreeStepContainer" />
    <assembly name="ThreeStepContainer" />
    <container>
      <register type="IDemoService" mapTo="AlternativeDemoService" />
    </container>
  </unity>
</configuration>

Tests

public class UnityContainerFactoryTests
{
    [Theory]
    [InlineData(true, typeof(AlternativeDemoService))]
    [InlineData(false, typeof(StandardDemoService))]
    public void Configuration(bool useConfig, Type expectedType)
    {
        using (var container=UnityContainerFactory.CreateContainer(useConfig))
        {
            var service = container.Resolve<IDemoService>();
            Assert.IsType(expectedType, service);
        }
    }
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics