我的 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;
}
In my MainForm
构造函数我有以下哪个有效:
private readonly ITest test;
public MainForm(ITest test)
{
this.test = test;
InitializeComponent();
}
容器已解析并且代码工作正常。问题/问题是,我如何实例化一个新表单MainForm
, say Form2
具有以下构造函数:
private readonly ISomeOtherTest someOtherTest;
public Form2(ISomeOtherTest someOtherTest)
{
this.someOtherTest = someOtherTest;
InitializeComponent();
}
如果我在我的MainForm
:
Form2 form2 = new Form2();
form2.Show();
它会崩溃,抱怨我没有向构造函数提供值。不过,我已经解决了我的容器,并且我认为所有下游容器都会得到解决。显然我在这里遗漏了一些东西,因为它不起作用。
这是否意味着我必须提前加载all依赖于MainForm
即使该表单不使用它,这样我就可以将它们传递给我所做的任何新表单实例化?如果我有 50 个依赖项需要解析,并且让顶级表单的构造函数将它们全部包含在内,那就很奇怪了。请帮助澄清我的理解,因为我几乎只在 Web API 和 MVC 中使用 Unity 和 DI 容器,而 MVC 已经为控制器内置了 DI 解析器,所以我必须在这里遗漏一些部分和理解。