简体   繁体   English

使用Ninject绑定到List <T>类型的已定义对象

[英]Bind to an defined object of type List<T> with Ninject

How can I do it with Ninject 我怎么能用Ninject做到这一点

var lst=new List<IAnimal>();
lst.Add(dog);
lst.Add(cat);

kernel.Bind<List<IAnimal>>().ToInstance(lst); 

What shall I use Instead of ToInstance() as Ninject doesn't have this method? 我应该使用什么而不是ToInstance()因为Ninject没有这种方法?

Looks like you can use ToConstant() : 看起来你可以使用ToConstant()

kernel.Bind<List<IAnimal>>().ToConstant(lst);

Though you may want to consider binding IList<IAnimal> rather than List<IAnimal> . 虽然您可能想要考虑绑定IList<IAnimal>而不是List<IAnimal>

EDIT: per your comment below 编辑:根据您的评论如下

ToMethod is another option, depending on your requirements. 根据您的要求, ToMethod是另一种选择。 This lets you use a Factory approach, where you can return a different instance based on external factors. 这使您可以使用Factory方法,您可以根据外部因素返回不同的实例。 For example: 例如:

kernel.Bind<IList<IAnimal>>().ToMethod(c => Helpers.IsDark ? return _nocturnalAnimals : return _allAnimals);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM