如何使用 Ninject 获取新对象,如本例所示
我需要添加一个 IVehicle 类型的项目,该项目在运行时从构造函数注入到 for 循环中。
IVehicle vehicle;
for (int i=0;i<=someValue;i++)
{
list.insert(i,vehicle);
//some processing to assign values
}
现在,因为此时 Ivehicle 已经注入,所以我的列表具有相同的值,尽管视图上的值不同并且通过控制器传递。我如何每次都更新这个对象
编辑
每次我发现更新这个对象的最佳方法是从注入它的内核请求新的。正如前面所说,我正在使用 Ninject。
我所做的就是使用创建一个 IKernel 类型的变量并让构造函数注入它,然后使用 kernel.Get() 获取一个新实例。不知道这是否是最好的方法,因为我的构造函数真的很贪婪。 :)
私有 IKernel _kernel;
将其注入到构造函数中,无需进行任何绑定,因为 Ninject 已经知道这一点。
然后您可以使用 _kernel.Get<>() 来获取新的 _kernel。
希望这对某人有帮助..
I am in need of adding an item of type IVehicle which is injected at runtime from constructor to a for loop.
IVehicle vehicle;
for (int i=0;i<=someValue;i++)
{
list.insert(i,vehicle);
//some processing to assign values
}
now because Ivehicle is already injected by this time, my list has same value despite the value on view different and coming through the controller. How can I new up this object everytime
EDIT
The best way to new up this object everytime I found was to request new from the kernel that was injecting it. I am using Ninject as said earlier.
All I did was use a create a variable of type IKernel and got the constructor to inject it and then I used kernel.Get() to get a new instance. Dont know if this is the best way to go about doing this as my constructor is really greedy. :)
private IKernel _kernel;
get this injected in constructor, no need to do any bindings as Ninject already knows this.
then you can use the _kernel to get new, by using _kernel.Get<>().
Hope this helps someone..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种情况的最佳方法是注入
Func
。并添加下面的绑定。这样您就不会在生产代码中引用 Ninject。此外,这种工厂方法计划添加到 Ninject 的下一个版本中。下面的绑定将不再需要。The best way for this scenario is to inject
Func<IVehicle>
. And add the binding below. That way you have no reference to Ninject in you production code. Furthermore this kind of factory methods are planned to be added to the next release of Ninject. The binding below will not be necessary anymore.