[英]How to bind IDictionary property with Ninject?
I have a class: 我有一节课:
public class MyClass
{
[Inject]
public IDictionary<string, IMyInterface> MyDictionary { get; set; }
}
I have several implementations of the IMyInterface
interface that have their own dependencies injected. 我有几个
IMyInterface
接口的IMyInterface
,它们注入了自己的依赖项。 Each implementation should have a different key. 每个实现都应该有不同的密钥。
How do I bind such a property using Ninject? 如何使用Ninject绑定这样的属性?
I assume this is a fixed list. 我认为这是一个固定的清单。 The easiest way would be with a provider:
最简单的方法是提供者:
public class MyProvider : IProvider
{
public object Create(IContext context)
{
return new Dictionary<string, IMyInterface>{
{"alpha", context.Kernel.Get<ImpClassOne>()},
{"beta", context.Kernel.Get<ImplClassTwo>()}
}
}
public Type Type
{
get { return typeof(IDictionary<string, IMyInterface>); }
}
}
You can register the provider to your kernel like: 您可以将提供程序注册到您的内核,如:
kernel.Bind<IDictionary<string, IMyInterface>>().ToProvider<MyProvider>();
and then the [Inject] for the property will use the provider to create the dictionary. 然后属性的[Inject]将使用提供程序来创建字典。
In case the key can somehow be retrieved/generated/calculated from IMyInterface
eg from a Name property then there is an easy solution. 如果可以以某种方式从
IMyInterface
检索/生成/计算密钥,例如从Name属性,那么有一个简单的解决方案。
public class DictionaryProvider : Provider<IDictionary<string, IMyInterface>>
{
private IEmumerable<IMyInterface> instances;
public DictionaryProvider(IEmumerable<IMyInterface> instances>)
{
this.instances = instances;
}
protected override IDictionary<string, IMyInterface> CreateInstance(IContext context)
{
return this.instances.ToDictionary(i => i.Name);
}
}
Otherwise ryber's solution is probably the easiest way to go. 否则,莱伯的解决方案可能是最简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.