问题
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