How to inject existing instance into target instance?

Nov 28, 2012 at 3:25 AM
Edited Nov 28, 2012 at 3:26 AM

I notice that each time when I resolve instance via Ninject kernel (call it InstanceA), Ninject will create a new dependency instance and inject it into my InstanceA.MyProperty.

What I want to achieve is, instead of Ninject to create a new copy of dependency instance, I want Ninject to inject the dependency instance that I have created manually into InstanceA.MyProperty.

I've tried for quite some while and have googled around but I couldn't get any solution. Following is my test code.

 

        IKernel kernel = new StandardKernel();
        kernel.Bind<IFood>().To<AnimalFood>();
        IFood food = kernel.Get<IFood>();
        food.FoodName = "Pizza";

        kernel.Bind<IAnimal>().To<Dog>().WithPropertyValue("MyFood", food);
        IAnimal bobbyDog = kernel.Get<Dog>();
        bobbyDog.Name = "Bobby";
        //kernel.Inject(bobbyDog);

 

I expect that the bobbyDog instance will get a food instance with FoodName = "Pizza". However, it turns out not the case.

Nov 28, 2012 at 4:20 AM

Alright, after numerous trial-and-error processes, I've got the solution and following is the working code:

        IKernel kernel = new StandardKernel();
        kernel.Bind<IFood>().To<AnimalFood>().WithPropertyValue("FoodName", "Pizza");
        IFood food = kernel.Get<IFood>();

        kernel.Bind<IAnimal>().To<Dog>().WithPropertyValue("Name", "Bobby");        
        IAnimal bobbyDog = kernel.Get<IAnimal>();

What happen is, I didn't aware that Ninject cannot inject string type value into property. Though I didn't test further, but I guess it applies the same for all other primitive types such as bool, int, etc.

The other mistake I made was, instead of kernel.Get<IDog>(), I code as kernel.Get<Dog>().