WindowsFormsLifetime icon indicating copy to clipboard operation
WindowsFormsLifetime copied to clipboard

Create scoped forms

Open Chri-s opened this issue 2 years ago • 3 comments

This pull request adds two functions (one async and one synchronous) to create a dependency injection scope when creating a Form via the IFormProvider.

Without this functions, when you create a Form and inject for example an efcore context, the context won't be disposed until you remember to dispose it when closing or disposing the form.

These two functions create a dependency injection scope for the form. So all transient and scoped service instances which are created for the form have the same lifetime as the form.

You can see this in the new tests. In the tests Dependencies_Not_Disposed_Without_A_Scope and Dependencies_Not_Disposed_Without_A_Scope_Async the dependencies are not disposed when the form is disposed. In the other two tests Dependencies_Disposed_With_Scope and Dependencies_Disposed_With_Scope_Async the transient and the scoped dependency are disposed when the form is disposed. The singleton service is not disposed.

Also two similar functions are added were you can give an existing scope to the function. Then the form will be created in the scope and the dependencies will be disposed if the scope is disposed. This can be seen in the two tests Dependencies_Disposed_With_Shared_Scope and Dependencies_Disposed_With_Shared_Scope_Async.

Chri-s avatar May 10 '23 19:05 Chri-s

This is a great addition. Thank you for the PR.

alex-oswald avatar Jul 10 '23 18:07 alex-oswald

I just committed the two lamda functions.

Chri-s avatar Jul 11 '23 11:07 Chri-s

I think I would rather create scopes by default, rather than adding new methods.

alex-oswald avatar Apr 26 '24 05:04 alex-oswald

Thank you. I should have a new release out within the next week.

alex-oswald avatar Apr 26 '24 20:04 alex-oswald