开发者

How to not pass around the container when using IoC in Winforms

I'm new to the world of IoC and having a problem with implementing it in a Win开发者_Go百科forms 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?


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:

builder.RegisterGeneratedFactory<Func<IDialogController>>();

Then in your main form:

class MainForm ... {

  Func<IDialogController> _controllerFactory;

  public MainForm(Func<IDialogController> controllerFactory) { ... }

  void ShowDialog() {
    using (var controller = _controllerFactory())
    {
    }
  }

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜