Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ninject

How can I do it with 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?

like image 830
Mehrdad Kamelzadeh Avatar asked Jan 17 '26 16:01

Mehrdad Kamelzadeh


1 Answers

Looks like you can use ToConstant():

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

Though you may want to consider binding IList<IAnimal> rather than List<IAnimal>.

EDIT: per your comment below

ToMethod is another option, depending on your requirements. This lets you use a Factory approach, where you can return a different instance based on external factors. For example:

kernel.Bind<IList<IAnimal>>().ToMethod(c => Helpers.IsDark ? return _nocturnalAnimals : return _allAnimals);
like image 193
Brian S Avatar answered Jan 20 '26 05:01

Brian S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!