How not to bypass a container when using IoC in Winforms

I am new to the IoC world and have a problem with its implementation in the Winforms application. I have an extremely basic Winform Application that uses MVC, this is one controller that does all the work and working dialogue (obviously with the controller). So I load all my classes into my IoC container in program.cs and create the main form controller using the container. But this is where I have problems, I just want to create a working controller dialog when it is used and inside the using statement.

At first I went into the container, but I read that this is bad practice, and more about the container is static, and I want to unit test this class.

So, how do you create classes in a friendly unit test without going through the container, I looked at the abstract factory template, but only this would solve my problem without using IoC.

I do not use any well-known frameworks, I borrowed the main 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 can I do this using IoC? Is this misuse for IoC?

+7
c # unit-testing inversion-of-control winforms
source share
3 answers

Ken post is very interesting, but you are at a point where you should learn more about IoC β€œproduction” containers, as some of them 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 populate the controllerFactory constructor parameter at run time. In your unit tests, you can easily create a lambda for the constructor.

+7
source share

Usually I just pass the interface to the factory class.

+1
source share

The only reasonable solution I came across is to make your Singleton container. Some of the IoC frameworks do this for you, but you may have to deploy your own Singleton implementation. Look at Jon Skeet ideas .

Good luck with MVC in Winforms. This is a steep learning curve that I am just starting to climb.

+1
source share

All Articles