Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register abstract class and resolve derived class with Unity

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?

like image 476
MicroMan Avatar asked May 23 '13 06:05

MicroMan


2 Answers

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");
like image 154
cuongle Avatar answered Sep 24 '22 09:09

cuongle


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

container.RegisterType<A, B>();
var b = container.Resolve<A>()
like image 41
NeddySpaghetti Avatar answered Sep 22 '22 09:09

NeddySpaghetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!