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();
}
}
}
}
}