Monday, November 28, 2011

Using Unity to Resolve Instances based on condition


Unity is a lightweight, extensible dependency injection container with support for nested containers that stores registrations and mappings between types and can instantiate the appropriate concrete types on demand. Identification of the registrations in unity can be done using a type and a name (optional).
You can use unity to register multiple implementations of the same type and later resolve the actual instance by passing the name for identifying the actual implementation. In this post we'll see how to resolve the instances registered in unity application block conditionally.
For e.g. I have created a sample interface and implementations as given below
public interface IMyObject
{
    string DoSomething();
}

public class MyObjectFirstImplementation : IMyObject
{
    public string DoSomething()
    {
        return "First";
    }
}

public class MyObjectSecondImplementation : IMyObject
{
    public string DoSomething()
    {
        return "Second";
    }
}

The registration of these components are done like
container
    .RegisterType<IMyObject, MyObjectFirstImplementation>(DependencyRegistrationKeys.FirstImplementation)
    .RegisterType<IMyObject, MyObjectSecondImplementation>(DependencyRegistrationKeys.SecondImplementation);

public static class DependencyRegistrationKeys
{
    public const string FirstImplementation = "FIRST_IMPLEMENTATION";
    public const string SecondImplementation = "SECOND_IMPLEMENTATION";
}

The factory class has a create method that accepts and object key to resolve the actual instances
public class MyObjectFactory
{
    public IMyObject Create(string objectKey)
    {
        return Container.Instance.Resolve<IMyObject>(objectKey);
    }
}

Tests
[TestMethod]
public void CreateMethodShouldReturnTheObjectImplementationBasedOnConditionPassed()
{
    var factory = new MyObjectFactory();
    var myObject = factory.Create(DependencyRegistrationKeys.FirstImplementation);

    Assert.IsInstanceOfType(myObject, typeof(MyObjectFirstImplementation));
}

No comments: