且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WinForm 应用程序中的 NHibernate 和 AUTOFAC

更新时间:2022-06-25 03:39:45

我会这样做

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;
    }
}

将您的 ISession 注册为 InstancePerLifetimeScope,Autofac 将在其作用域被释放时对其进行处理.在这个例子中,我使用了FormScope"标签,这样如果我不小心尝试解析另一个范围(可能是***容器范围)之外的 ISession ,Autofac 将抛出异常.>

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.