Inject Specific Type With Autofac

僤鯓⒐⒋嵵緔 提交于 2019-12-11 02:23:08

问题


I want to inject specific type when some conditions are met. For example, i have got an interface like below.

public interface IMyInterface{

}

And also two classes that implement this interface

public class MyClassA : IMyInterface {
}

and

public class MyClassB : IMyInterface {
}

Finally i have some service class that gets a constructor parameter as IMyInterface.

public class ServiceA{
private IMyInterface _interfaceClass;
public ServiceA(IMyInterface interfaceClass){
_interfaceClass = interfaceClass
}
}

and

public class ServiceB{
private IMyInterface _interfaceClass;
public ServiceA(IMyInterface interfaceClass){
_interfaceClass = interfaceClass
}
}

Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.

Normally i am using Autofac like below

var builder = new ContainerBuilder();
builder.RegisterType<MyClassA>().As<IMyInterface>().InstancePerApiRequest();

But i couldn't find the way how can i force Autofac to select right type for specific type. I looked to Named<> feature but couldn't solve problem.


回答1:


It sounds like you have violated Liskov substitution principle

Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.

I'm not sure that Autofac supports context based injection - why don't you just make each Service dependent on the implementation it requires?

public class ServiceA
{
    private IMyInterface _interfaceClass;
    public ServiceA(MyClassA interfaceClass)
    {
        _interfaceClass = interfaceClass
    }
}


来源:https://stackoverflow.com/questions/16699588/inject-specific-type-with-autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!