How do I get a new object using Ninject as in this example

百般思念 提交于 2019-12-05 07:32:19

问题


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


回答1:


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>()));


来源:https://stackoverflow.com/questions/4781479/how-do-i-get-a-new-object-using-ninject-as-in-this-example

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