Trying to inject dependencies to usercontrols in WinForms. As the instantiation of controls is generated by designer, only setter injection seems to be possible. My objective is to directly reference DI container only at the form level:
public void Form(StructureMap.Container container)
{
InitializeComponent();
container.BuildUp(this); // this should also traverse Controls and their subcontrols
}
The problem is how to force DI container to traverse the Controls collection hierarchically and inject dependencies. Is this possible with any DI container? Trying with StructureMap and so far no luck:
Container container = new Container(delegate (ConfigurationExpression e)
{
InjectedClass c = new InjectedClass();
e.Policies.SetAllProperties(delegate (StructureMap.Configuration.DSL.SetterConvention x)
{
x.OfType<InjectedClass>();
});
e.For<InjectedClass>().Use(c);
});
Form form1 = new Form(container);
// here the form.Controls[0].Controls[0].MyInjectedClass has no instance
StructureMap seems to stop at the first level (injecting to Form.MyInjectedClass
is working)
I Couldn't do it either. I used structuremap with setter injection and called ObjectFactory.BuildUp in every control.
Define a CustomInjectAttribute
Define a Registry
Then call BuildUp on Control's constructor: