4

I'm looking for a good tutorial to configure AUTOFAC with NHibernate in a WinForm application injecting the ISession when a form is created and disposing the ISession on form close.

I found a lot of MVC and ASP.NET example but none using WinForm.

Can you point me in the right direction?

danyolgiax
  • 12,798
  • 10
  • 65
  • 116
  • Have a look at: http://stackoverflow.com/questions/3521813/nhibernate-winforms-castle-windsor-session-management – DanP Jan 12 '12 at 17:37

2 Answers2

3

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 dispose of it when its scope is disposed. In this example, I am using the "FormScope" tag so that if I accidentally try to resolve an ISession out of another scope (maybe the top-level container scope) Autofac will throw 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 Save or something), and it probably should rollback the transaction if the user clicks Cancel. Implicit rollback is not recommended.

default.kramer
  • 5,943
  • 2
  • 32
  • 50
0

I know it's too late and danyolgiax already found a solution. Yesterday I was wondering how to combine Autofac with MVP in Winforms. I came into this article.

It's written in Polish, so feel free to use a translator. The idea presented is very neat, clear and I'll certainly follow it when we'll migrate to Autofac with our project. I thought it's worth keeping it here for people that should run into the same problem.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
dzendras
  • 4,721
  • 1
  • 25
  • 20