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.
source share