使用 Windows 窗体的 StructureMap
我习惯于将 StructureMap 与 Web 应用程序一起使用...但现在,我正在开发一个 Windows 窗体项目,我想使用它,但我不知道如何配置它。
在网络中,我有一个在 Global.asax 上的 Application_Start 上调用的引导程序类,但我不知道如何在 WinForms 上执行相同的操作。
谢谢!
I'm used to work with StructureMap with Web Apps... but now, I'm working on a Windows Forms project and I'd like to use it, but I don't how to configure it.
In web, I'd have a bootstrapper class that is invoked on Application_Start on Global.asax, but I don't know how to do the same on WinForms.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在启动应用程序的静态 main 方法中初始化容器。然后从容器中检索表单实例,以便可以注入任何必要的依赖项。您仍然可以将初始化代码放入引导程序中。
You can initialize the container in the static main method that starts your application. Then retrieve your form instances from the container, so that any necessary dependencies can be injected. You could still put the initialization code in a Bootstrapper.
对于 Winforms 应用程序,Application_Start 的对应部分将是初始化第一个表单的主要方法。
在 Web 应用程序中使用 ORM 映射器时,您通常有为每个 http 请求创建数据上下文/会话的经验法则。对于 Winforms 应用程序,您倾向于为每个操作或每个表单提供一个上下文。
For a Winforms application the counter part to Application_Start would be the main method that initializes the first Form.
When using ORM mappers with web applications you generally have the thumb rule of creating a data context/session per http request. For a Winforms application you tend to go for a context per operation or per form.
您可以以相同的方式构建引导和 IoC 配置(尽管我不确定如何包含表单类本身,我没有太多使用 WinForms)。您需要的唯一真正的区别是调用初始化程序的时间/地点。它只需在应用程序的启动过程中即可。对于 Web 应用程序,您确实可以从 Application_Start 调用它。我认为在 WinForms 应用程序中,它将位于 OnLoad 中主窗体的事件。
如果您在任何地方都有一个
main
方法(类似于控制台应用程序),那么它也可以工作。例如,如果 WinForms 应用程序是从控制台应用程序移植的,则可能会出现这种情况。You'd structure the bootstrapping and IoC configuration in the same ways (though I'm not sure how you'd include the form classes themselves, I haven't worked with WinForms much). The only real difference that you'd need is when/where the initializer gets called. It just has to be in the startup of the application. For web applications, you do indeed call it from Application_Start. I think in WinForms apps it would be in the OnLoad event of the main form.
If you have a
main
method anywhere (similar to a console app) then that would work as well. This could be if the WinForms app was ported from a console app, for example.