在Winforms中使用IoC时如何不传递容器
我是 IoC 世界的新手,并且在 Winforms 应用程序中实现它时遇到问题。我有一个非常基本的应用程序 Winform 应用程序,它使用 MVC,它是一个完成所有工作的控制器和一个工作对话框(显然带有一个控制器)。因此,我将所有类加载到 program.cs 中的 IoC 容器中,并使用该容器创建主表单控制器。但这就是我遇到问题的地方,我只想在使用时并在 using 语句内创建工作对话框控制器。
起初我传入了容器,但我读到这是不好的做法,而且容器是静态的,我想对这个类进行单元测试。
那么如何以单元测试友好的方式创建类而不传入容器,我正在考虑抽象工厂模式,但仅此一项就可以在不使用 IoC 的情况下解决我的问题。
我没有使用任何著名的框架,我从这篇博客文章中借用了一个基本框架 http://www.kenegozi.com/Blog/2008/01/17/its-my-turn -to-build-an-ioc-container-in-15-minutes-and-33-lines.aspx
如何使用 IoC 执行此操作?这是 IoC 的错误使用吗?
I'm new to the world of IoC and having a problem with implementing it in a Winforms application. I have an extremely basic application Winform application that uses MVC, it is one controller that does all the work and a working dialog (obviously with a controller). So I load all my classes in to my IoC container in program.cs and create the main form controller using the container. But this is where I am having problems, I only want to create the working dialog controller when it's used and inside a using statement.
At first I passed in the container but I've read this is bad practice and more over the container is a static and I want to unit test this class.
So how do you create classes in a unit test friendly way without passing in the container, I was considering the abstract factory pattern but that alone would solve my problem without using the IoC.
I'm not using any famous framework, I borrowed a basic one from this blog post http://www.kenegozi.com/Blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines.aspx
How do I do this with IoC? Is this the wrong use for IoC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ken 的帖子非常有趣,但您现在值得了解更多有关“生产”IoC 容器的信息,因为现在有一些容器支持这种情况。
例如,在 Autofac 中,您可以“生成”一个工厂作为委托:
然后在您的主窗体中:
Autofac 将在运行时填写controllerFactory 构造函数参数。在单元测试中,您可以轻松地向构造函数提供 lambda。
Ken's post is very interesting, but you're at the point where it is worth learning more about the "production" IoC containers, as a few now support this scenario.
In Autofac for example, you can 'generate' a factory as a delegate:
Then in your main form:
Autofac will fill in the controllerFactory constructor parameter at runtime. In your unit tests you can easily provide a lambda to the constructor instead.
我通常只是将接口传递给工厂类。
I generally just pass in an interface to a factory class.
我想到的唯一合理的解决方案是让你的容器成为单例。一些 IoC 框架可以为您做到这一点,但您可能必须推出自己的 Singleton 实现。看看 Jon Skeet 的想法。
祝 Winforms 中的 MVC 好运。这是一条陡峭的学习曲线,我才刚刚开始上升。
The only reasonable solution I came around with is making your container Singleton. Some of the IoC frameworks do that for you, but you might have to roll out your own implementation of Singleton. Have a look at Jon Skeet's ideas.
Good luck with MVC in Winforms. It is a steep learning curve, that I am only beginning to ascend on.