NHibernate and AUTOFAC in WinForm application

后端 未结 2 932
暖寄归人
暖寄归人 2020-12-15 14:35

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 fo

2条回答
  •  不思量自难忘°
    2020-12-15 15:05

    I would do something like this

    public class FormFactory
    {
        readonly ILifetimeScope scope;
    
        public FormFactory(ILifetimeScope scope)
        {
            this.scope = scope;
        }
    
        public TForm CreateForm() where TForm : Form
        {
            var formScope = scope.BeginLifetimeScope("FormScope");
            var form = formScope.Resolve();
            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()
        .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.

提交回复
热议问题