这是在网络应用程序环境:

的初始请求是能够成功地完成,但是任何其他要求返回来自NHibernate的框架一个“会话被关闭”的响应。我使用的是HTTP模块的方法用下面的代码:

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 类似的问题在这里。在我的实现使用WebSessionContext我也是,但是,液体不超过编写自定义SessionManager提供的其他。对于简单的CRUD操作,是从撕开所需自定义会话提供商内置工具(即WebSessionContext)?

有帮助吗?

解决方案

我还没有测试的代码,但是从读取,这一行:

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();
}

其他提示

我得到一个类似的错误。原来我的“新”荷兰国际集团我的资料库,而不必我的IOC容器解决。

下面的语句使用处置或关闭每个查询后关闭会话:

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

而是使用它没有“使用”字为:

ISession session = SessionFactory.Instance.GetCurrentSession()

这为我工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top