使用Autofac注入特定类型 [英] Inject Specific Type With Autofac
问题描述
我想在满足某些条件时注入特定类型.例如,我有一个如下所示的界面.
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 {
}
和
public class MyClassB : IMyInterface {
}
最后,我有一些服务类将构造函数参数作为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
}
}
和
public class ServiceB{
private IMyInterface _interfaceClass;
public ServiceA(IMyInterface interfaceClass){
_interfaceClass = interfaceClass
}
}
现在由于某些体系结构限制, ServiceA必须将MyClassA作为构造函数参数,而 ServiceB必须将MyClassB作为构造函数参数.
Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.
通常我像下面那样使用Autofac
Normally i am using Autofac like below
var builder = new ContainerBuilder();
builder.RegisterType<MyClassA>().As<IMyInterface>().InstancePerApiRequest();
但是我找不到方法如何强制Autofac为特定类型选择正确的类型.
我查看了Named<>
功能,但无法解决问题.
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.
推荐答案
听起来您违反了Liskov替代原则
It sounds like you have violated Liskov substitution principle
现在由于某些体系结构限制,ServiceA必须将MyClassA作为构造函数参数,而ServiceB必须将MyClassB作为构造函数参数.
Now because of some architectural constraints ServiceA must get MyClassA as constructor parameter and ServiceB must get MyClassB as constructor parameter.
我不确定Autofac是否支持基于上下文的注入-为什么不仅使每个Service依赖于其所需的实现?
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
}
}
这篇关于使用Autofac注入特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!