使用Ninject注入一个集合

时间:2015-06-30 12:08:49

标签: c# .net c#-4.0 dependency-injection ninject

我们假设我有以下课程:

public class AsyncEntityManager<E> : EntityManager<E>, IAsyncEntityManager<E>
      where E : IPersistableEntity
{
     public AsyncEntityManager(ICollection<IPersistenceStrategy<E>> strategies, ILogger logger) : base(strategies, logger) { }
}

在这种情况下如何注入集合?

这就是我的尝试:

internal class PersistenceModule : ApplicationModule
{
     public override void Load()
     {
          Kernel.Bind<ICollection<IPersistenceStrategy<User>>>().ToMethod(c => new IPersistenceStrategy<User>[] {
               (IPersistenceStrategy<User>)c.Kernel.GetService(typeof(DynamoDBStrategy<User>))
          });

          Kernel.Bind<IAsyncEntityManager<User>>().To<AsyncEntityManager<User>>();
     }
}

然而,该集合没有元素注入。它是 null,但它根本没有任何元素。尽管如此,ILoggeer正在被注射得很好。

1 个答案:

答案 0 :(得分:0)

For anyone interested, it seems Ninject can handle multipible bindings to the same interface:

Kernel.Bind<IPersistenceStrategy<User>>().To<DynamoDBStrategy<User>>();
Kernel.Bind<IPersistenceStrategy<User>>().To<SQLServerStrategy<User>>();

This will be injected as a IPersistenceStrategy<User>[], which is then casted to ICollection<IPersistenceStrategy<User>>