开发者

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. Each implementation should have a different key.

How d开发者_Go百科o I bind such a property using 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.


In case the key can somehow be retrieved/generated/calculated from IMyInterface e.g. from a Name property then there is an easy solution.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜