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

Mir*_*ral 3 nhibernate hibernateexception

当我试图获取CurrentSession时,我收到此错误

NHibernate.Context.CurrentSessionContext.CurrentSession()
Run Code Online (Sandbox Code Playgroud)

NHibernate.Impl.SessionFactoryImpl.GetCurrentSession()
Run Code Online (Sandbox Code Playgroud)

Cal*_*bHC 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个自定义的HttpModule,它在每个请求中绑定我的会话,然后我将这个模块添加到我的web.config中,如下所示:

<httpModules>
  <add name="NHHttpModule" type="MyApplication.Core.NHHttpModule, MyApplication,
  Version=1.0.0.0, Culture=neutral" />      
</httpModules>
Run Code Online (Sandbox Code Playgroud)

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


Tim*_*han 11

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


Dav*_*d M 6

您负责在会话上下文中设置当前会话.请参阅NHibernate文档的此部分.如果您还没有这样做,那么将不会检索当前会话.