How to use DI when spawning new Windows Forms downstream?

﹥>﹥吖頭↗ 提交于 2019-12-05 16:59:22

You should create your form like so

Form2 form = container.Resolve<Form2>();

You were not using the container, therefore the Form does not have a constructor which takes no arguments. If you resolve it with the container, it will examine the constructor, find the dependencies and automatically inject them into the constructor for you.

So.. maybe your problem is that you do not have access to the container in your MainForm? If this is the problem there are two approaches..

Inject IUnityContainer into MainForm constructor

However... people who live by the "composition root" pattern will tell you that you should only use the container from the root of your application (in this case, probably Main() ) The other option is...

Create a Form2 factory class from your composition root (Main) which gets injected into MainForm and MainForm uses the factory to create Form2

You should read more into the Composition Root theory of thinking...

Composition Root


update

I've never had to do it before, but I think the second method would look something like this...

public class Form2Factory : IForm2Factory
{
    private readonly ISomeOtherTest someOtherTest;

    public Form2Factory(ISomeOtherTest someOtherTest)
    {
        this.someOtherTest = someOtherTest;
    }

    public Form2 Create()
    {
        return new Form2(someOtherTest);
    }
}


public class MainForm
{
    private readonly IForm2Factory form2Factory;

    public MainForm(IForm2Factory form2Factory)
    {
        this.form2Factory = form2Factory;
    }

    private void DoingSomething()
    {
        Form2 form = form2Factory.Create();
        form.Show();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!