views:

67

answers:

2

I'm sure I'm doing something stupid but this is what we're here for!

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?

+2  A: 

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
}
Kevin Babcock
Thanks Kevin, it fixes the problem, but I think I'm after a better solution.I keep reading about the "bad smell" of lots of inject and get calls, as it's not true DI. I'm trying property injection, as constructor injection just seems to get in the way whenever I instantiate an object. Having an instance of the kernel also seems backwards?
mattdwen
A: 

Instead of doing

var form = new MainForm()

...

class MainForm
{
    MainForm()
    {
        GlobalKernel.Inject(this)

....

You want to be doing:

var form = Kernel.Get<MainForm>()

Which obviates the need for the explicit Inject (and allows you to do constructor injection).

I dont know of any WinForms (or WPF) samples for Ninject (but it'd be a good question to ask and/or stick a bounty on -- IIRC one came up recently)

See also:

http://stackoverflow.com/questions/693690/ioc-di-framworks-with-smart-client-winform-apps-how-should-i-approach-this

http://stackoverflow.com/questions/3493932/what-is-the-best-practice-for-winforms-dialogs-with-ninject

Ruben Bartelink