通过实现IHttpModule初始化Nhibernate的Session
Nhibernate的Session如果每次都打开,关闭一次会很麻烦,如果忘记关闭Session,很容易就达到连接池的最大值,我们可以把他移动到实现IHttpModule的类中
在请求开始时初始化CoreRepository,并且放入每次请求缓存(HttpContent.Item)中
参考Cuyahoga的实现
using System;
using System.Web;
using VirtualBank.Service;
namespace VirtualBank.Web.HttpModules
{
/// <summary>
/// Http module that manages the NHibernate sessions during an HTTP Request.
/// </summary>
public class NHSessionModule : IHttpModule
{
/// <summary>
/// Default constructor.
/// </summary>
public NHSessionModule()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
context.EndRequest += new EventHandler(Context_EndRequest);
}
public void Dispose()
{
// Nothing here
}
private void Context_BeginRequest(object sender, EventArgs e)
{
// Create the repository for Core objects and add it to the current HttpContext.
CoreRepository cr = new CoreRepository(true);
HttpContext.Current.Items.Add("CoreRepository", cr);
}
private void Context_EndRequest(object sender, EventArgs e)
{
// Close the NHibernate session.
if (HttpContext.Current.Items["CoreRepository"] != null)
{
CoreRepository cr = (CoreRepository)HttpContext.Current.Items["CoreRepository"];
cr.CloseSession();
}
}
}
}
using System.Web;
using VirtualBank.Service;
namespace VirtualBank.Web.HttpModules
{
/// <summary>
/// Http module that manages the NHibernate sessions during an HTTP Request.
/// </summary>
public class NHSessionModule : IHttpModule
{
/// <summary>
/// Default constructor.
/// </summary>
public NHSessionModule()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
context.EndRequest += new EventHandler(Context_EndRequest);
}
public void Dispose()
{
// Nothing here
}
private void Context_BeginRequest(object sender, EventArgs e)
{
// Create the repository for Core objects and add it to the current HttpContext.
CoreRepository cr = new CoreRepository(true);
HttpContext.Current.Items.Add("CoreRepository", cr);
}
private void Context_EndRequest(object sender, EventArgs e)
{
// Close the NHibernate session.
if (HttpContext.Current.Items["CoreRepository"] != null)
{
CoreRepository cr = (CoreRepository)HttpContext.Current.Items["CoreRepository"];
cr.CloseSession();
}
}
}
}
在Web.config
中注册Module
<httpModules>
<add type="VirtualBank.Web.HttpModules.NHSessionModule, VirtualBank" name="NHSessionModule" />
</httpModules>
<add type="VirtualBank.Web.HttpModules.NHSessionModule, VirtualBank" name="NHSessionModule" />
</httpModules>
调用方法:
通常可以放到构造函数中
_coreRepository = HttpContext.Current.Items["CoreRepository"] as CoreRepository;
可以参考:
操作Nhibernate