会话已在ASP .NET Session Per Request模式中关闭

时间:2012-10-31 08:44:39

标签: asp.net nhibernate ado.net

我在ASP .NET Web窗体应用程序中使用Session Per Request方法。

这是请求结束时运行的代码,这就是我关闭会话的方式:

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionFactoryProvider.SessionFactory);

        if (session != null)
        {
            if (session.Transaction != null && session.Transaction.IsActive)
            {
                session.Transaction.Rollback();
            }
            if (session.IsOpen)
            {
                session.Close();    
            }
        }
    }

非常明显的东西。但是,在调用 session.Close 时,我经常遇到异常。例外是 SessionException ,消息为:

  

{“会话已经关闭”}

堆栈跟踪是:

   at NHibernate.Impl.SessionImpl.Close() in d:\CSharp\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 343

我正在使用的NHibernate版本是: 3.0.0.4000

我已经搜索了可以关闭会话的代码,但是没有找到任何代码。此外,我已经使用对会话对象无效的简单请求进行了测试,但仍然是相同的。有什么想法可能是什么问题?

编辑:在分裂和征服会话之后,我定位了一段负责该异常的代码

                    var session = SessionFactoryProvider.GetCurrentSession();
                    using (ITransaction tx = session.BeginTransaction())
                    {
                        session.Update(instrument);
                        tx.Commit();
                    }

如果我发表评论,会话在EndRequest处理程序中顺利关闭,并且没有会话已经关闭会抛出异常。

2 个答案:

答案 0 :(得分:1)

我们正在使用IHttpModule

public class ModuleSessionNHibernate : IHttpModule
{
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginTransaction);
            context.EndRequest += new EventHandler(CommitAndCloseSession);
        }

        private void CommitAndCloseSession(object sender, EventArgs e)
        {
            // commit or rollback depending on errors
            // then close session
        }

        ...
}

在web.config中

<httpModules>
    <add name="NHibernateSessionModule" type="XXX.ModuleSessionNHibernate, XXX"/>
</httpModules>

编辑:关于提交和关闭会话(但我们使用了很多帮助和服务...)

    private void CommitAndCloseSession(object sender, EventArgs e)
    {
        try
        {
            if (no exception in context)
            {
                // commit transaction
            }
            else
            {
                // rollback transaction
            }
        }
        finally
        {
            try
            {
                // close session
            }
            catch (Exception ex)
            {
                // send email                       
            }

                // rollback
                // close

                throw;
            }
        }
    }

答案 1 :(得分:1)

通过迁移到NHibernate 3.3.1解决了问题。

然而,其他问题浮出水面:

Could not find the property - exception after switching from NHibernate 3 to 3.3.1