[转]Web项目下NHibernate的Session管理的解决方案


NHibernate的Session的管理一直是个问题,在系统开发中

如果有lazy="true",如果不对Session进行管理,会抛出以下错误:
CODE:

Failed to lazily initialize a collection - no session
[Copy to clipboard]


在Web项目下的解决方案,就是在Application_BeginRequest方法中打开Session并放入HttpContext,在Application_EndRequest方法中关闭Sesssion就可以了。

还好,NHibernate1.2已经提供了相关的支持,如下:

在web.config中加入以下代码
CODE:

<httpModules>
        <add name="CurrentSessionModule" type="NHibernate.Example.Web.CurrentSessionModule" />
    </httpModules>
[Copy to clipboard]



程序如下:

CODE:

using System;
using System.Web;
using NHibernate.Context;

namespace NHibernate.Example.Web
{
  public class CurrentSessionModule : IHttpModule
  {
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
        context.EndRequest += new EventHandler(Application_EndRequest);
    }

    public void Dispose()
    {
    }

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        ManagedWebSessionContext.Bind(HttpContext.Current, ExampleApplication.SessionFactory.OpenSession());
    }

    private void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, ExampleApplication.SessionFactory);
  if(session !=null)
  {
        if (session.Transaction.IsActive)
        {
          session.Transaction.Rollback();
        }

        if (session != null)
        {
          session.Close();
        }
    }
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值