Ninject for winforms - does my architecture make this useless?

I'm trying out Ninject with a winforms app (basically a sketch, I'm using it sort of like a kata, but nothing so rigorous or specific) in .net 4.

To create the main form, I'm doing something like:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        [...]
        IKernel kernel = BuildKernel();
        Application.Run(kernel.Get<frmMain>());
    }

    static IKernel BuildKernel()
    {
        var modules = new INinjectModule[] 
        { 
            [..modules]
        };

        return new StandardKernel(modules);
    }
}

Fine. This creates a main form and displays it nicely, passing the appropriate interface implementations to the injected constructor.

Now what? My application is an MDI and will have several child windows for manipulating the application model. I don't have a reference to the kernel anymore, so how am I supposed to Get() these forms? The obvious answer is 'pass the kernel to the form' I suppose, but that's a horribly messy strategy and I'm sure that doesn't fit into the philosophy of DI.

I will point out here that the documentation for Ninject 2 sucks. Everything I can find repeats the basic examples, without really explaining how DI using Ninject makes anything easier. The standard of example given isn't complicated enough to make the trouble of coding and creating modules and bindings worthwhile.

edit #1:

Having studied the links kindly provided by Sam Holder, I'm trying out the 'composition root' approach. My architecture now forces all the Forms it uses to derive from a CompositedForm with constructor semantics thus:

    [Inject]
    public CompositingForm(ICompositionRoot CompositionRoot)
    {
        InitializeComponent();
        this.CompositionRoot = CompositionRoot;
    }
    public readonly ICompositionRoot CompositionRoot;

    public CompositingForm() : this(new DummyCompositionRoot()) { }

The second constructor is for the benefit of the Forms Designer, which is stupid and can't understand the form markup unless you provide an empty constructor. Now, every form created using IKernel.Get() will (should) have a composition root injected into it.

So, as I am a slow learner - now the question is really 'What should go in this composition root'?

6
задан Tom W 17 December 2010 в 17:09
поделиться