如果这是一个愚蠢的问题,我会事先道歉:我对NInject很新。
我需要使用多个集合初始化我的应用程序,每个集合都有几个相同的对象。如果没有IoC,那将是:
public ICollection<ICollection<IBusinessObject>> Piles = new ICollection<ICollection<IBusinessObject>>();
public MyCollectionContainer()
{
Piles.Add(new List<IBusinessObject>({ new ObjectA(), new ObjectA() });
Piles.Add(new List<IBusinessObject>({ new ObjectB(), new ObjectB() });
Piles.Add(new List<IBusinessObject>({ new ObjectC(), new ObjectC() });
}
我想指示NInject为我做这项工作,以便拨打Kernel.Get<MyCollectionContainer>()
可以完成与上述相同的工作,当然还有一些额外的灵活性。
换句话说,我想在绑定时指示NInject
Kernel.Bind<ICollection<ICollection<IBusinessObject>>>().To< /* A list of 3 */>();
Kernel.Bind<IList<IBusinessObject>>().To< /* A List of 2 IBusinessObject */>();
Kernel.Bind<IBusinessObject>().To< /* a different type depending on the container */>();
附带问题:我应该更好地使用Kernel.Get<MyCollectionContainer>()
或Kernel.Get<ICollection<ICollection<IBusinessObject>>>()
编辑:在搜索解决方案时,我尝试在
模型中为我的馆藏定义自定义绑定Kernel.Bind<IList<IBusinessObject>>()
.ToConstructor(x => new List<IBusinessObject>(
x.Inject<IList<IBusinessObject>>())
);
使用扩展方法IConstructorArgumentSyntax.InjectMany(int i)
:
Kernel.Bind<IList<IBusinessObject>>().To<ObjectA>();
Kernel.Bind<IList<IBusinessObject>>()
.ToConstructor(x => new List<IBusinessObject>(
x.InjectMany<IList<IBusinessObject>>(2))
);
public static T InjectMany<T>(this IConstructorArgumentSyntax x, int numberOfInjections)
{
/* loop */
{
x.Inject<T>();
}
}
可悲的是,NInject拒绝调用x.Inject();抱怨说我已经潜入了他们的魔法:
System.InvalidOperationException :
This method is for declaration that a parameter shall
be injected only! Never call it directly.