NHibernate版本:2.1
我正在使用似乎非常标准的 HttpModule 方法来在 ASP.NET+NHibernate 应用程序中实现每个请求会话。我正在尝试利用杠杆WebSessionContext
,但它似乎无法正常工作。具体来说,对于应用程序上的第一个请求,一切都运行良好,但其他请求会导致“会话已关闭!”任何时候使用会话时都会出现异常。重置应用程序池允许另一个请求成功,然后更多“会话已关闭!”。
有一些感人的片段,但我不太了解上下文是如何缩小范围的,所以......这就是一切!
在 web.config 中:
<property name="current_session_context_class">
NHibernate.Context.WebSessionContext, NHibernate
</property>
(我也尝试将其设置为“网络”,结果相同。)
确认模块配置正确:
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
Debug.WriteLine("NHibernateSessionModule.Init()");
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.BeginRequest()");
var session = NHibernateHelper.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.EndRequest()");
var session = NHibernateHelper.GetCurrentSession();
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
throw new ApplicationException("Error committing database transaction", ex);
}
finally
{
session.Close();
}
}
CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
}
}
还有我的小帮手:
public class NHibernateHelper
{
public static readonly ISessionFactory SessionFactory;
static NHibernateHelper()
{
try
{
Configuration cfg = new Configuration();
cfg.AddAssembly(Assembly.GetCallingAssembly());
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw new ApplicationException("NHibernate initialization failed", ex);
}
}
public static ISession GetCurrentSession()
{
return SessionFactory.GetCurrentSession();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
NHibernate 1.2 的示例(来自 NHibernate in Action)显示取消绑定是在关闭之前完成的。
这种顺序的改变有帮助吗?
var session = NHibernateHelper.GetCurrentSession();
CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
...
session.Close();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)