问题描述
我正在尝试使用Ninject将IEnumerable
注入到构造函数中.
I'm trying to inject an IEnumerable
into a constructor with Ninject.
我的构造函数如下:
public MatrixViewModel(IEnumerable<FooViewModel> fooViewModels)
{
_fooViewModels = fooViewModels;
}
我的Ninject模块如下所示:
My Ninject module looks like this:
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从未使用过绑定,传递给构造函数的值基本上只是一个空的默认值.
This doesn't seem to be working. I don't get any error. Ninject just doesn't ever use the binding, and the value that is passed into the constructor is basically just an empty default value.
如何使用Ninject注入IEnumerable
?
How do you inject an IEnumerable
with Ninject?
修改
有关我的工厂方法的更多详细信息:
More details on my factory method:
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循环来一次绑定一个视图模型:
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);
}
推荐答案
根据Remo的回答,一种可能的解决方案是使用foreach
循环一次绑定一个视图模型:
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);
}
这篇关于使用Ninject工厂方法将IEnumerable注入构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!