Setter injection with hierarchical controls in Winforms

103 views Asked by At

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)

1

There are 1 answers

0
Pablo Rausch On

I Couldn't do it either. I used structuremap with setter injection and called ObjectFactory.BuildUp in every control.

Define a CustomInjectAttribute

public class CustomInjectAttribute : Attribute
{
}

Define a Registry

public class MyRegistry : Registry
{
    public MyRegistry()
    {
         this.Policies.SetAllProperties(by => by.Matching(prop => prop.HasAttribute<CustomInjectAttribute>()));
    }
}

Then call BuildUp on Control's constructor:

    public partial class MyControl : UserControl
{
    public MyControl()
    {
        this.InitializeComponent();
        ObjectFactory.BuildUp(this);
    }

    [CustomInject, Browsable(false)]
    public IInjectable Injectable { protected get; set; }
}