NHibernate.HibernateException:没有绑定到当前上下文的会话

时间:2009-07-17 14:22:29

标签: nhibernate hibernateexception

当我尝试获取CurrentSession

时,我收到此错误
NHibernate.Context.CurrentSessionContext.CurrentSession()

at

NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()

3 个答案:

答案 0 :(得分:13)

就像David M所说,你需要确保绑定你的NHibernate会话。这是我现在在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,它在每个请求中绑定我的会话,然后我将这个模块添加到我的web.config中,如下所示:

<httpModules>
  <add name="NHHttpModule" type="MyApplication.Core.NHHttpModule, MyApplication,
  Version=1.0.0.0, Culture=neutral" />      
</httpModules>

我确定你的配置与此不同,但这只是我如何绑定会话的一个例子。希望这有点帮助。

答案 1 :(得分:11)

Studio 2010将创建2个httpModules部分,一个用于IIS 7.请务必在system.web中注册您的nhibernate httpmodule。

答案 2 :(得分:6)

您负责在会话上下文中设置当前会话。请参阅NHibernate文档的this section。如果您还没有这样做,那么将无法检索当前会话。

相关问题