“会话已关闭!" -NHibernate [英] "Session is Closed!" - NHibernate
问题描述
这是在Web应用程序环境中:
This is in a web application environment:
初始请求能够成功完成,但是任何其他请求都会从NHibernate框架返回会话已关闭"响应.我正在使用带有以下代码的HttpModule方法:
An initial request is able to successfully complete, however any additional requests return a "Session is Closed" response from the NHibernate framework. I'm using a HttpModule approach with the following code:
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对象.
SessionFactory.Instance is my singleton implementation, using FluentNHibernate to return an ISessionFactory object.
在我的存储库类中,我尝试使用以下语法:
In my repository class, I attempt to use the following syntax:
public class MyObjectRepository : IMyObjectRepository
{
public MyObject GetByID(int id)
{
using (ISession session = SessionFactory.Instance.GetCurrentSession())
return session.Get<MyObject>(id);
}
}
这允许这样调用应用程序中的代码:
This allows code in the application to be called as such:
IMyObjectRepository repo = new MyObjectRepository();
MyObject obj = repo.GetByID(1);
我怀疑应该归咎于我的存储库代码,但是我不确定100%应该使用的实际实现.
I have a suspicion my repository code is to blame, but I'm not 100% sure on the actual implementation I should be using.
我在此处上发现了类似的问题.我也在实现中使用WebSessionContext,但是,除了编写自定义SessionManager之外,没有提供其他解决方案.对于简单的CRUD操作,除了内置工具(即WebSessionContext)以外,是否还需要自定义会话提供程序?
I found a similar issue on SO here. I too am using WebSessionContext in my implementation, however, no solution was provided other than writing a custom SessionManager. For simple CRUD operations, is a custom session provider required apart from the built in tools(ie WebSessionContext)?
推荐答案
我尚未测试您的代码,但从阅读此行来看:
I haven't tested your code, but from reading, this line:
using (ISession session = SessionFactory.Instance.GetCurrentSession())
在该区块退出后正在转储您的会话,然后该会话在下一次通过时被处置/无效.
is dumping your session after the block exits, and then the session is disposed/invalid on the next time through.
这是我们在应用程序中使用的模型:
Here's the model we're using in our applications:
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();
}
这篇关于“会话已关闭!" -NHibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!