相关疑难解决方法(0)

如何在下游生成新的Windows窗体时使用DI?

我有Unity DI容器最初使用我的Windows窗体应用程序.在Program.cs我有以下几点:

static void Main()
{
    var container = BuildUnityContainer();
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(container.Resolve<MainForm>());
}

private static IUnityContainer BuildUnityContainer()
{
    var container = new UnityContainer();
    container.RegisterType<ITest, MyTestClass>();
    container.RegisterType<ISomeOtherTest, MyOtherClass>();
    return container;
}
Run Code Online (Sandbox Code Playgroud)

在我的MainForm构造函数中,我有以下工作:

private readonly ITest test;

        public MainForm(ITest test)
        {
            this.test = test;
            InitializeComponent();
        }
Run Code Online (Sandbox Code Playgroud)

容器已解析,代码正常.问题/问题是,我如何实例化一个新表单MainForm,比如说Form2有以下构造函数:

private readonly ISomeOtherTest someOtherTest;

    public Form2(ISomeOtherTest someOtherTest)
    {
       this.someOtherTest = someOtherTest;
       InitializeComponent();
    }
Run Code Online (Sandbox Code Playgroud)

如果我在我的尝试中尝试以下内容MainForm:

Form2 form2 = new Form2();
form2.Show(); …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection unity-container winforms

4
推荐指数
1
解决办法
4048
查看次数