Question

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?

Was it helpful?

Solution

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");

OTHER TIPS

Given a unity container container, you should be able to do

container.RegisterType<A, B>();
var b = container.Resolve<A>()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top