Register abstract class and resolve derived class with Unity

MicroMan picture MicroMan · May 23, 2013 · Viewed 7.3k times · Source

I have the following code

public abstract class A
{
    public abstract string MethodA();
}

public class B : A
{

    public override string MethodA()
    {
        return "Class B method";
    }
}

public class C : A
{

    public override string MethodA()
    {
        return "Class C method";
    }
}

I would like to register and resolve the concrete implementations using service locator. Is this possible?

Answer

cuongle picture cuongle · May 23, 2013

Yes, possible, you can register using the name:

 var container = new UnityContainer();
 container.RegisterType<A, B>("B");
 container.RegisterType<A, C>("C");

And then you can resolve based on the name like below:

 A b = container.Resolve<A>("B");
 A C = container.Resolve<A>("C");