gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:14:58 24 4
gpt4 key购买 nike

我尝试在 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();

关于Autofac WithKey 属性未按预期工作(多个实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36633241/

24 4 0