[英]Autofac two properties with the same type
如果我在具有相同接口類型的類中有兩個屬性,並且我想為每個類型注入兩種不同的conrete類型,我如何使用屬性或構造函數注入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?
使用屬性注入,您可以執行以下操作:
builder.RegisterType<A>()
.As<IA>()
.OnActivating(e =>
{
e.Instance.PropertyB = e.Context.Resolve<BImpl1>();
e.Instance.PropertyC = e.Context.Resolve<BImpl2>();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.