代码之家  ›  专栏  ›  技术社区  ›  Alexis Abril

“会话已关闭!”-NHibernate

  •  6
  • Alexis Abril  · 技术社区  · 16 年前

    这是在web应用程序环境中:

    初始请求能够成功完成,但是任何其他请求都会从NHibernate框架返回“会话已关闭”响应。我正在使用带有以下代码的HttpModule方法:

    public class MyHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.EndRequest += ApplicationEndRequest;
            context.BeginRequest += ApplicationBeginRequest;
        }
    
        public void ApplicationBeginRequest(object sender, EventArgs e)
        {
            CurrentSessionContext.Bind(SessionFactory.Instance.OpenSession());
        }
    
        public void ApplicationEndRequest(object sender, EventArgs e)
        {
            ISession currentSession = CurrentSessionContext.Unbind(
                SessionFactory.Instance);
    
            currentSession.Dispose();
        }
    
        public void Dispose() { }
    }
    

    在我的repository类中,我尝试使用以下语法:

    public class MyObjectRepository : IMyObjectRepository
    {
        public MyObject GetByID(int id)
        {
            using (ISession session = SessionFactory.Instance.GetCurrentSession())
                return session.Get<MyObject>(id);
        }
    }
    

    IMyObjectRepository repo = new MyObjectRepository();
    MyObject obj = repo.GetByID(1);
    

    我怀疑是我的存储库代码造成的,但我不能100%确定我应该使用的实际实现。

    我发现了一个类似的问题 here . 我也在我的实现中使用WebSessionContext,但是,除了编写自定义SessionManager之外,没有提供任何解决方案。对于简单的CRUD操作,除了内置工具(即WebSessionContext)之外,是否还需要自定义会话提供程序?

    3 回复  |  直到 9 年前
        1
  •  4
  •   Jon Seigel    16 年前

    我尚未测试您的代码,但通过阅读,这行代码:

    using (ISession session = SessionFactory.Instance.GetCurrentSession())

    以下是我们在应用程序中使用的模型:

    ISession session = null;
    
    try
    {
        // Creates a new session, or reconnects a disconnected session
        session = AcquireCurrentSession();
    
        // Database operations go here
    }
    catch
    {
        session.Close();
        throw;
    }
    finally
    {
        session.Disconnect();
    }
        2
  •  0
  •   Tuan    15 年前

    我也犯了类似的错误。原来我是在“新建”我的存储库,而不是让我的IOC容器解决它。

        3
  •  0
  •   Brick    9 年前

    using (ISession session = SessionFactory.Instance.GetCurrentSession())
    

    相反,使用它时不要使用“using”一词:

    ISession session = SessionFactory.Instance.GetCurrentSession()
    

    这对我有用。