How to associate an IDictionary property with a 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. Each implementation must have a different key.

How to bind such a property using Ninject?

+4
source share
2 answers

I assume this is a fixed list. The easiest way is with the 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 in your kernel, for example:

  kernel.Bind<IDictionary<string, IMyInterface>>().ToProvider<MyProvider>(); 

and then [Inject] for the property will use the provider to create the dictionary.

+4
source

In case the key can somehow be extracted / generated / calculated from IMyInterface , for example. from the Name property, then there is a simple 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, the ryber solution is probably the easiest way.

+3
source

Source: https://habr.com/ru/post/1369139/


All Articles