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

时间:2016-04-14 20:22:01

标签: autofac linqpad

我试图在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)没有返回预期的实例。我在这里做错了什么?

1 个答案:

答案 0 :(得分:5)

看起来你忘记了to register the consumers using WithAttributeFilter这就是允许它工作的原因。像:

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