作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试在 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/
我尝试在 LinqPad 中重建问题: /* “Named and Keyed Services” http://autofac.readthedocs.org/en/latest/a
以下代码有效(我可以无限期地重复播放声音): SKAction *playMusic = [SKAction playSoundFileNamed:@"sound.m4a" waitForComple
我是一名优秀的程序员,十分优秀!