NHibernate and AUTOFAC in a WinForm Application

I am looking for a good tutorial to configure AUTOFAC using NHibernate in a WinForm application that injects ISession when creating a form and deleting ISession on the form.

I found many examples of MVC and ASP.NET, but none of them used WinForm.

Can you point me in the right direction?

+4
source share
2 answers

I would do something like this

public class FormFactory { readonly ILifetimeScope scope; public FormFactory(ILifetimeScope scope) { this.scope = scope; } public TForm CreateForm<TForm>() where TForm : Form { var formScope = scope.BeginLifetimeScope("FormScope"); var form = formScope.Resolve<TForm>(); form.Closed += (s, e) => formScope.Dispose(); return form; } } 

Register your ISession as InstancePerLifetimeScope , and Autofac will get rid of it when its scope is deleted. In this example, I use the "FormScope" tag so that if I accidentally try to allow ISession from another area (possibly the top-level container area), Autofac throws an exception.

 builder.Register(c => SomeSessionFactory.OpenSession()) .As<ISession>() .InstancePerMatchingLifetimeScope("FormScope"); 

Your code will have to commit the transaction explicitly (probably when the user clicks the "Save" button or something else), and probably he should cancel the transaction if the user clicks "Cancel". Direct rollback is not recommended.

+3
source

I know this is too late, and danyolgiax already found a solution. Yesterday I was wondering how to combine Autofac with MVP in Winforms. I came to this one.

It is written in Polish, so feel free to use a translator. The idea presented is very neat, clear, and I will definitely follow it when we get to Autofac with our project. I thought it was worth keeping it here for people who should face the same problem.

0
source

Source: https://habr.com/ru/post/1389684/


All Articles