开发者

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

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<=someValu开发者_开发问答e;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..


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜