Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 解决多密钥服务_C#_Autofac - Fatal编程技术网

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