Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Injector - Windows Forms Example Broken

I'm trying to use Simple Injector in a Windows Forms application. Unfortunately, the documentation at https://simpleinjector.readthedocs.org/en/latest/windowsformsintegration.html is not correct or is out of date.

When you actually run the example, it results in the following error: The configuration is invalid. The following diagnostic warnings were reported: -[Disposable Transient Component] MainView is registered as transient, but implements IDisposable.

Furthermore, the app I'm building is a Winforms MVP (passive view) project. I can change the scope of MainView to singleton and it works. But for the life of me, I cannot figure out how to open other windows because of this scoping issue. Has anyone successfully used SimpleInjector in a real-world MVP winforms application with multiple windows? I'm curious to see how Presenters, Forms/Views, and the Main entry point are configured and what their Lifestyle scopes are.

Just for reference, I've tried using LifetimeScoping and ExecutionContextScoping extensions, but absolutely nothing has worked. Maybe it's just a PEBKAC issue.

Thanks, Eric

like image 520
Eric Wallace Avatar asked Nov 05 '15 21:11

Eric Wallace


2 Answers

Use container.RegisterSingleton< "object" >();

http://simpleinjector.readthedocs.org/en/latest/lifetimes.html

like image 75
André Monteiro Avatar answered Oct 23 '22 10:10

André Monteiro


I've had a very similar issue with an old Winforms app that I am trying to refactor.

In my case, and I am sure in yours too, the form is created using Application.Run(). If we look at this stackoverflow link, it mentions that the dispose() method will be automatically called by the runtime.

This means that we can safely ignore the warning for this win form registration as described in the simpleinjector docs.

The code would look something like:

Registration registration = _container.GetRegistration(typeof(MainView)).Registration;
registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent, "Main Windows Form (MainView) will be automatically disposed by runtime as it is registered using Application.Run()");
like image 25
Praval 'Shaun' Tirubeni Avatar answered Oct 23 '22 11:10

Praval 'Shaun' Tirubeni