如本例所示,如何使用Ninject获取新对象 [英] How do I get a new object using Ninject as in this example

查看:105
本文介绍了如本例所示,如何使用Ninject获取新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加一个IVehicle类型的项,该项在运行时从构造函数注入到for循环中.

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
}

现在因为Ivehicle已经被注入,所以我的列表具有相同的值,尽管视图上的值不同并且通过控制器进入.我怎么每次都可以更新这个对象

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

编辑

每次发现这个对象的最佳方法是从注入它的内核中请求新的对象.如前所述,我正在使用Ninject.

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.

我所做的只是使用创建IKernel类型的变量并让构造函数注入它,然后使用kernel.Get()获得一个新实例.不知道这是否是执行此操作的最佳方法,因为我的构造函数确实很贪婪. :)

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. :)

私有IKernel _kernel;

private IKernel _kernel;

将其注入构造函数中,无需进行任何绑定,因为Ninject已经知道了这一点.

get this injected in constructor, no need to do any bindings as Ninject already knows this.

然后,您可以使用_kernel.Get<>()使用_kernel来获取新的内容.

then you can use the _kernel to get new, by using _kernel.Get<>().

希望这对某人有帮助.

推荐答案

此方案的最佳方法是注入Func<IVehicle>.并在下面添加绑定.这样,您就无需在生产代码中引用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.

Bind<Func<IConfigurationView>>().ToMethod(ctx => (() => ctx.Kernel.Get<IConfigurationView>()));

这篇关于如本例所示,如何使用Ninject获取新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆