Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject property injection returns null

I've got a WinForms app with the following code:

static void Main()
{
    IKernel kernel = new StandardKernel(new MyModule());
    TestInterface test = kernel.Get<TestInterface>();
}

For the Module.Load() event:

Bind<TestClass>().ToSelf().InSingletonScope();
Bind<TestInterface>().To<TestClass>();

At this point test in the Main() method is the proper object I'm expecting.

In a form later on, I'm using property injection:

[Inject]
TestInterface test {get;set;}

And once the form is loaded, trying to work with test, but it's a null object.

Thoughts?

like image 973
mattdwen Avatar asked Aug 24 '10 00:08

mattdwen


1 Answers

Make sure you call Inject() on the IKernel instance and pass in an instance of your form. This will ensure all dependencies are properly injected. For example...

[Inject]
TestInterface Test { get; set; }

private void Form_Load(object sender, EventArgs e)
{            
    IKernel kernel = ... // Get an instance of IKernel
    kernel.Inject(this);

    // Your form dependencies have now been injected and the 
    // Test property is ready to use
}
like image 116
Kevin Babcock Avatar answered Oct 05 '22 07:10

Kevin Babcock