"会议已结束!" - NHibernate

Ale*_*ril 6 c# nhibernate session repository-pattern

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

初始请求能够成功完成,但是任何其他请求都会从NHibernate框架返回"Session is Closed"响应.我正在使用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() { }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

这允许应用程序中的代码被调用:

IMyObjectRepository repo = new MyObjectRepository();
MyObject obj = repo.GetByID(1);
Run Code Online (Sandbox Code Playgroud)

我怀疑我的存储库代码应该受到责备,但我并不是100%肯定我应该使用的实际实现.

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

Jon*_*gel 4

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

using (ISession session = SessionFactory.Instance.GetCurrentSession())
Run Code Online (Sandbox Code Playgroud)

在块退出后转储您的会话,然后该会话在下次通过时被处置/无效。

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

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();
}
Run Code Online (Sandbox Code Playgroud)