如何使用 Nhibernate 在 asp.net mvc 中实现 session-per-request 模式 [英] How to implement session-per-request pattern in asp.net mvc with Nhibernate

查看:14
本文介绍了如何使用 Nhibernate 在 asp.net mvc 中实现 session-per-request 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 global.asax 文件的 Application_start 事件中创建了 nhibernate 会话,该会话正在传递给服务方法的构造函数.

I created the nhibernate session in Application_start event of global.asax file,the session is being passed to constructors of service methods.

在服务方法中,我使用会话来执行 CRUD 操作,这很好用.但是,当多个请求或并行事务发生时 nhibernate 会抛出一些异常.阅读论坛后我才知道 Nhibernate 会话不是线程安全的.如何使其线程安全并让我的应用程序 (ASP.NET mvc) 与并行事务一起工作?

In the service method I am using the session to do CRUD operations, this works fine.However, When multiple requests or parallel transactions occuring nhibernate is throwing some exceptions.After reading forums i came to know that Nhibernate session is not thread safe.How to make it thread safe and let my application (ASP.NET mvc) work with parallel trandsactions?

推荐答案

让线程安全的唯一方法是为每个请求创建一个新会话,你可以使用 current_session_context_class 属性来NHibernate 配置中的 managed_web.

Only way to make it thread safe is to create a new session per each request, you could use current_session_context_class property to managed_web in NHibernate config.

在 global.asax 中

In global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var session = SessionFactory.OpenSession();
        CurrentSessionContext.Bind(session);
    }

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        var session = CurrentSessionContext.Unbind(SessionFactory);
        //commit transaction and close the session
    }

现在当你想访问会话时,你可以使用,

now when you want to access the session, you could use,

Global.SessionFactory.GetCurrentSession()

如果您使用的是 DI 容器,它通常内置于容器中,

If you are using a DI container, it's usually built into the container,

例如 Autofac(参见这个问题 了解更多信息),

For example for Autofac (see this question for more information),

containerBuilder.Register(x => {
    return x.Resolve<ISessionFactory>().OpenSession(); 
}).As<ISession>().InstancePerHttpRequest();

这篇关于如何使用 Nhibernate 在 asp.net mvc 中实现 session-per-request 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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