【问题标题】:"Session is Closed!" - NHibernate“会话已关闭!” - NHibernate
【发布时间】:2010-11-29 14:19:24
【问题描述】:

这是在网络应用环境中:

初始请求能够成功完成,但是任何其他请求都会从 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() { }
}

SessionFactory.Instance 是我的单例实现,使用 FluentNHibernate 返回一个 ISessionFactory 对象。

在我的存储库类中,我尝试使用以下语法:

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% 确定我应该使用的实际实现。

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

【问题讨论】:

    标签: c# nhibernate session repository-pattern


    【解决方案1】:

    我还没有测试过你的代码,但是通过阅读,这一行:

    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】:

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

      【讨论】:

        【解决方案3】:

        使用以下语句会在每次查询后处理或关闭会话:

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

        而是使用它而不使用“使用”一词:

        ISession session = SessionFactory.Instance.GetCurrentSession()
        

        这对我有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-18
          • 2012-11-10
          • 2019-09-11
          相关资源
          最近更新 更多