我有一个将接口作为构造函数参数的类。这个接口有两种实现,我想根据一个变量来决定在运行时使用什么实现。
问题是上面的类在 Autofac 解决的对象层次结构中很深,所以我不能传递参数。
像下面这样的东西是我想要实现的。
public interface IInterface1 {}
public interface IInterface2 {}
public class Class1 : IInterface2
{
public Class1(IInterface1 interface1)
{
}
}
public class Class2
{
public Class2(IInterface2 interface2)
{
}
}
public class Class3
{
public void GetClass2Instance(string interface1ImplementationToChoose)
{
// want to change which implementation of IInterface1 is resolved based on the interface1ImplementationToChoose variable
var class2 = container.Resolve<Class2>();
}
}
有任何想法吗?
更新:
澄清一下,这是一个现有的对象层次结构,由运行良好的现有应用程序使用。此外,对象模型比本示例中显示的模型大得多。因此,我真的不想将工厂传递给对象图中的每个构造函数,以供该图中深处的类使用。
有没有办法在 Class2 不知道的情况下将 IInterface1 的不同实现传递给 Class1?
谢谢