您的位置:首页 > 其它

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

2007-11-07 10:47 141 查看
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();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: