在Winforms中使用分层控件的Setter注入

时间:2016-12-18 17:30:35

标签: c# winforms dependency-injection structuremap

尝试将依赖项注入WinForms中的usercontrols。由于控件的实例化是由设计者生成的,因此只有setter注入才有可能。 我的目标是仅在表单级别直接引用DI容器:

public void Form(StructureMap.Container container)
{
   InitializeComponent();
   container.BuildUp(this); // this should also traverse Controls and their subcontrols
}

问题是如何强制DI容器分层遍历Controls集合并注入依赖项。任何DI容器都可以吗?尝试使用StructureMap,到目前为止没有运气:

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似乎停在第一级(注入Form.MyInjectedClass正在运行)

1 个答案:

答案 0 :(得分:0)

我也无法做到。 我使用带有setter注入的structuremap,并在每个控件中都调用了ObjectFactory.BuildUp。

定义CustomInjectAttribute

public class CustomInjectAttribute : Attribute
{
}

定义注册表

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

然后在Control的构造函数上调用BuildUp:

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

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