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

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

问题描述

我在找一个很好的教程中注入的Isession创建一个表单时和形式接近的处置ISession的一个WinForm应用程序与NHibernate配置AUTOFAC。

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.

我发现使用WinForm的很多MVC和ASP.NET的例子,但没有。

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.

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

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