C# 解决多密钥服务
我不确定我错过了什么。我有多组从单个接口派生的服务。每个组都需要单独解决:C# 解决多密钥服务,c#,autofac,C#,Autofac,我不确定我错过了什么。我有多组从单个接口派生的服务。每个组都需要单独解决: builder.RegisterType<Bar1>().Keyed<IFoo>("Bars"); builder.RegisterType<Bar2>().Keyed<IFoo>("Bars"); builder.RegisterType<Foo1>().Keyed<IFoo>("Foos"); builder.RegisterType<Fo
builder.RegisterType<Bar1>().Keyed<IFoo>("Bars");
builder.RegisterType<Bar2>().Keyed<IFoo>("Bars");
builder.RegisterType<Foo1>().Keyed<IFoo>("Foos");
builder.RegisterType<Foo2>().Keyed<IFoo>("Foos");
builder.RegisterType().Keyed(“条”);
builder.RegisterType().Keyed(“条”);
builder.RegisterType().Keyed(“Foos”);
builder.RegisterType().Keyed(“Foos”);
什么是有效的:
var keyfoos = scope.ResolveKeyed<IEnumerable<IFoo>>("Foos");
Console.Write("resolved keyfoos: ");
Console.WriteLine(foos == null ? "null" : keyfoos.Count().ToString());
var-keyfoos=scope.resolvedkeyed(“Foos”);
Console.Write(“已解决的keyfoos:”);
Console.WriteLine(foos==null?“null”:keyfoos.Count().ToString());
已解决的关键问题:2
实际的问题是注入这些键控服务:
public class FooBar
{
public FooBar(
[KeyFilter("Foos")]
IEnumerable<IFoo> foos,
[KeyFilter("Bars")]
IEnumerable<IFoo> bars)
{
Console.Write("ctor key foos: ");
Console.WriteLine(foos == null ? "null" : foos.Count().ToString());
Console.Write("ctor key bars: ");
Console.WriteLine(bars == null ? "null" : foos.Count().ToString());
}
}
scope.Resolve<FooBar>();
公共类FooBar
{
公共餐厅(
[键过滤器(“Foos”)]
数不清的食物,
[键过滤器(“条”)]
(可数条)
{
Console.Write(“ctor键foos:”);
Console.WriteLine(foos==null?“null”:foos.Count().ToString());
控制台。写入(“ctor键栏:”);
Console.WriteLine(bar==null?“null”:foos.Count().ToString());
}
}
scope.Resolve();
结果:
关键字:0
关键栏:0
我希望两个“列表”的计数都是2而不是0。我缺少什么?使用
KeyFilterAttribute
向构造函数注册类还需要WithAttributeFiltering()
而不是:
builder.RegisterType<FooBar>().AsSelf();
builder.RegisterType().AsSelf();
我需要
builder.RegisterType<FooBar>().AsSelf().WithAttributeFiltering();
builder.RegisterType().AsSelf().WithAttributeFilter();
所以现在的结果是:
主要食物:2
关键栏:2