下游生成新Windows窗体时如何使用DI?我有最初在我的Windows窗体应用程序中使用的UnityDI容器。在Program.cs中,我有以下内容:staticvoidMain(){varcontainer=BuildUnityContainer();Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(容器.Resolve());}privatestaticIUnityContainerBuildUnityContainer(){varcontainer=newUnityContainer();容器.RegisterType();容器.RegisterType();返回容器;在我的MainForm构造函数中,我有以下工作:privatereadonlyITesttest;publicMainForm(ITesttest){this.test=test;初始化组件();容器已解析,代码工作正常。问题/问题是,我如何从MainForm实例化一个新表单,比如Form2具有以下构造函数:privatereadonlyISomeOtherTestsomeOtherTest;publicForm2(ISomeOtherTestsomeOtherTest){this.someOtherTest=someOtherTest;初始化组件();MainForm尝试以下操作:Form2form2=newForm2();form2.Show();它中断了,抱怨我没有为构造函数提供值。但我已经解决了我的容器,我认为所有下游容器都将得到解决。显然我在这里遗漏了一些东西,因为它不起作用。这是否意味着我必须将所有依赖项加载到MainForm中,即使该表单不使用它,以便我可以将它们传递给我创建的任何新表单实例?如果我有50个依赖关系要解决并且顶级表单的构造函数解决了它们,那将很奇怪。请帮助澄清我的理解,因为我几乎只在WebAPI和MVC中使用Unity和DI容器,它们已经为控制器内置了DI解析器,所以我必须在这里遗漏一些部分和理解。您应该像这样创建表单Form2form=container.Resolve();您没有使用容器,因此Form没有不带参数的构造函数。如果你使用容器来解决它,它会检查构造函数,找到依赖项并自动将它们注入到构造函数中。所以..也许您的问题是您无权访问MainForm中的容器?如果这是问题所在,有两种方法......将IUnityContainer注入MainForm构造函数但是......以“组合根”模式为生的人会告诉你你应该只在应用程序的根目录中使用容器(在这种情况下,可能是Main())另一种选择是......从组合根(Main)创建一个Form2工厂类,它被注入到MainForm中,MainForm使用工厂创建Form2你应该阅读更多关于理论的信息compositionrootthinking...CompositionRootUPDATE我以前从来没有这样做过,但我认为第二种方法看起来像这样...以上是C#学习教程:HowtouseDIwhengeneratingnewWindowsFormsdownstream?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——publicclassForm2Factory:IForm2Factory{privatereadonlyISomeOtherTestsomeOtherTest;publicForm2Factory(ISomeOtherTestsomeOtherTest){this.someOtherTest=someOtherTest;}publicForm2Create(){returnnewForm2(someOtherTest);}}publicclassMainForm{privatereadonlyIForm2Factoryform2Factory;publicMainForm(IForm2Factoryform2Factory){this.form2Factory=form2Factory;创造();形式.显示();}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系如管理员删除,如有转载,请注明出处:
