Dependency Injection into Winform UserControls

Jan 14, 2009 at 2:53 PM
Hi all,

Appologies if this has been answered somewhere, but im a little stuck.

I am trying to use Unity setter injection to wire up a UserControl dependency on a WinForm.

I can use Unity to create an instance of the Form, but is there any way to use setter injection on the embedded user control dropped by the designer?
The only way i can currently see is to have the same setter property dependency on the WinForm and manually call the usercontrol setter property.

Is there a better way?

Currently the usercontrol uses a singleton to access a live database, which is obviously not good.

Jan 18, 2009 at 5:29 AM
The issue is that the code that creates the user control is written by the WinForms designer and it doesn't call the container, it just news up the control. So you can't do constructor injection. You can do property injection, but you'll need to do something like this:

        static void Main()

            IUnityContainer container = new UnityContainer();

                new InjectionProperty("InjectedText", "I was injected"));

            Form mainForm = container.Resolve<Form1>();

            foreach(Control c in mainForm.Controls)
                container.BuildUp(c.GetType(), c);


The important thing here is the foreach loop over mainForm.Controls. That'll walk the control tree and inject whatever properties you need. Note that this only goes one level deep, to the direct children of mainForm. If you want to hit children of children etc, you'll need to make that a recursive loop.

Jan 19, 2009 at 8:09 AM
Edited Jan 19, 2009 at 10:21 AM
Hi Chris, thanks for your reply.

I dont really like the solution, but it works - thanks.

Is there any way in future to resolve this say using class attributes on user controls etc?
I appreciate the correct way forward would be to remove the problem logic out of the view. I am currently working on a rather old codebase which will take me till i retire to do that for all cases :)
Jan 19, 2009 at 6:08 PM
The fundamental issue is that the code to create the controls is written by the winforms designer, and there's no hook to take over the calls. So we're kind of stuck.

I can see writing a custom resolver that could do the buildup call automatically - that way all you'd need to do is create public properties that expose your user control objects to the container. Hrm... will have to think about that a little more.