【发布时间】:2012-06-27 07:50:26
【问题描述】:
如果我在一个类中有两个具有相同接口类型的属性,并且我想向每个属性注入两个不同的具体类型,我该如何使用 autofac 进行属性或构造函数注入。
例如。
class A : IA
{
public IB PropertyB { get; set; }
public IB PropertyC { get; set; }
public A(IB b, IB c)
{
PropertyB = b;
PropertyC = c;
}
public void PrintB()
{
PropertyB.Print();
}
public void PrintC()
{
PropertyC.Print();
}
}
我已经尝试过了,但当然我只是将 C 注入到这两个属性中
var builder = new ContainerBuilder();
builder.RegisterType<B>().As<IB>();
builder.RegisterType<C>().As<IB>();
builder.RegisterType<A>().As<IA>();
var container = builder.Build();
var a = container.Resolve<IA>();
或者这个结果相同:
builder.RegisterType<B>().As<IB>();
builder.RegisterType<C>().As<IB>();
builder.RegisterType<A>().As<IA>().PropertiesAutowired();
var container = builder.Build();
var a = container.Resolve<IA>();
有没有办法告诉 autofac 我想要 PropertyB 中的 B 和 PropertyC 中的 C ?
【问题讨论】: