1
votes

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
Consider describing you problem more in detail. You want to add someValue times a vehicle or what?Remo Gloor

1 Answers

2
votes

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