我试图将一个IEnumerable注入到Ninject的构造
函数中.
我的构造函数如下所示:
- public Matrixviewmodel(IEnumerable<Fooviewmodel> fooviewmodels)
- {
- _fooviewmodels = fooviewmodels;
- }
我的Ninject模块如下所示:
- public class MainModule : NinjectModule
- {
- public override void Load()
- {
- Bind<IEnumerable<Fooviewmodel>>()
- .ToMethod(context => GetFooviewmodels())
- .InSingletonScope(); // this binding is not working
- }
-
- private IEnumerable<Fooviewmodel> GetFooviewmodels()
- {
- // returns a bunch of foo view models
- }
- }
这似乎没有工作.我没有任何错误. Ninject只是不使用绑定,并且传递给构造函数的值基本上只是一个空的默认值.
如何注册一个IEnumerable与Ninject?
编辑
关于我工厂方法的更多细节:
- private IEnumerable<Fooviewmodel> GetFooviewmodels()
- {
- return new[]
- {
- new Fooviewmodel
- {
- Bar = new Barviewmodel
- {
- X = 1,Y = 2
- },Misc = "Hello"
- },new Fooviewmodel
- {
- Bar = new Barviewmodel
- {
- X = 3,Y = 4
- },Misc = "Goodbye"
- },// etc.....
- };
- }
编辑2
基于Remo的答案,一个可能的解决方案是使用foreach循环来一次绑定视图模型:
- foreach (var fooviewmodel in GetFooviewmodels())
- {
- Bind<Fooviewmodel>().ToConstant(fooviewmodel);
- }