WinForm 应用程序中的 NHibernate 和 AUTOFAC [英] NHibernate and AUTOFAC in WinForm application

查看:50
本文介绍了WinForm 应用程序中的 NHibernate 和 AUTOFAC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个很好的教程来在 WinForm 应用程序中使用 NHibernate 配置 AUTOFAC,在创建表单时注入 ISession,并在表单关闭时处理 ISession.

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.

我发现了很多 MVC 和 ASP.NET 示例,但没有一个使用 WinForm.

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

你能指出我正确的方向吗?

Can you point me in the right direction?

推荐答案

我会这样做

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.

这篇关于WinForm 应用程序中的 NHibernate 和 AUTOFAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆