当我尝试获取 CurrentSession 时出现此错误
NHibernate.Context.CurrentSessionContext.CurrentSession()
在
NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()
最佳答案
就像 David M 说的,你需要确保你绑定(bind)了你的 NHibernate session 。这是我现在在我的 ASP.NET 应用程序中执行此操作的方式:
public class NHHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += ApplicationEndRequest;
context.BeginRequest += ApplicationBeginRequest;
}
public void ApplicationBeginRequest(object sender, EventArgs e)
{
CurrentSessionContext.Bind(NHSessionFactory.GetNewSession());
}
public void ApplicationEndRequest(object sender, EventArgs e)
{
ISession currentSession = CurrentSessionContext.Unbind(
NHSessionFactory.GetSessionFactory());
currentSession.Close();
currentSession.Dispose();
}
public void Dispose()
{
// Do nothing
}
}
我创建了一个自定义 HttpModule,它在每个请求上绑定(bind)我的 session ,然后我将此模块添加到我的 web.config 中,如下所示:
<httpModules>
<add name="NHHttpModule" type="MyApplication.Core.NHHttpModule, MyApplication,
Version=1.0.0.0, Culture=neutral" />
</httpModules>
我确定您的配置与此不同,但这只是我如何绑定(bind) session 的示例。希望这有所帮助。
关于NHibernate.HibernateException : No session bound to the current context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143611/