Autofac WithKey 属性未按预期工作(多个实现)

Autofac WithKey Attribute not working as expected (multiple implementations)

我尝试在 LinqPad 中重建问题:

/*
    “Named and Keyed Services”
    http://autofac.readthedocs.org/en/latest/advanced/keyed-services.html
*/

const string A = "a";
const string B = "b";
const string MyApp = "MyApp";

void Main()
{
    var builder = new ContainerBuilder();
    builder
        .RegisterType<MyClassA>()
        .As<IMyInterface>()
        .InstancePerLifetimeScope()
        .Keyed<IMyInterface>(A);
    builder
        .RegisterType<MyClassB>()
        .As<IMyInterface>()
        .InstancePerLifetimeScope()
        .Keyed<IMyInterface>(B);
    builder
        .RegisterType<MyAppDomain>()
        .Named<MyAppDomain>(MyApp);

    var container = builder.Build();

    var instance = container.ResolveKeyed<IMyInterface>(A);
    instance.AddTheNumbers().Dump();

    var myApp = container.ResolveNamed<MyAppDomain>(MyApp);
    myApp.Dump();
}

interface IMyInterface
{
    int AddTheNumbers();
}

class MyClassA : IMyInterface
{
    public int AddTheNumbers() { return 1 + 2; }
}

class MyClassB : IMyInterface
{
    public int AddTheNumbers() { return 3 + 4; }
}

class MyAppDomain
{
    public MyAppDomain([WithKey(A)]IMyInterface aInstance, [WithKey(B)]IMyInterface bInstance)
    {
        this.ANumber = aInstance.AddTheNumbers();
        this.BNumber = bInstance.AddTheNumbers();
    }

    public int ANumber { get; private set; }

    public int BNumber { get; private set; }

    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendFormat("ANumber: {0}", this.ANumber);
        sb.AppendFormat(", BNumber: {0}", this.BNumber);
        return sb.ToString();
    }
}

MyApp 被“转储”时,我看到 ANumber: 7, BNumber: 7 告诉我 WithKey(A) 没有返回预期的实例。我在这里做错了什么?

您好像忘记了 to register the consumers using WithAttributeFilter 这正是它起作用的原因。喜欢:

builder.RegisterType<ArtDisplay>().As<IDisplay>().WithAttributeFilter();