Injecting an IEnumerable into a constructor with a Ninject factory method

China☆狼群 提交于 2019-12-05 03:56:47

Enumerables are treated differently by Ninject. Just provide bindings for all the view models. For enumerables Ninject will create an instance of every applying binding and pass them as IEnumerable.

e.g.

Bind<FooViewModel>().To<FooViewModel1>();
Bind<FooViewModel>().To<FooViewModel2>();

Based on Remo's answer, one possible solution is to use a foreach loop to bind the view models one at a time:

foreach (var fooViewModel in GetFooViewModels())
{
    Bind<FooViewModel>().ToConstant(fooViewModel);
}

From your question:

Bind<IEnumerable<FooViewModel>>()
    .ToMethod(context => GetFooViewModels())

I am not sure collection support or ToMethod works that way.

This should would work though:

Bind<MatrixViewModel>()
    .ToMethod(context => new MatrixViewModel(GetFooViewModels()))

Of course, how useful this solution is depends on how you're building up your views.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!