`
hugh-lin
  • 浏览: 70368 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

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

阅读更多

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

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

Failed to lazily initialize a collection - no session


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

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

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

<httpModules>
        <add name="CurrentSessionModule" type="NHibernate.Example.Web.CurrentSessionModule" />
    </httpModules>



程序如下:

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();
        }
    }
    }
  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics