NHibernateのバージョン:2.1セッションごとのNHリクエスト - 「セッションは終了しました!」
私はASP.NET + NHibernateのアプリケーションで要求ごとのセッションを実装するにはかなりの標準的なHttpModuleをアプローチであると思われるものを使用しています。 WebSessionContext
を利用しようとしていますが、正しく動作していないようです。具体的には、アプリケーションの最初のリクエストではすべてがうまく動作しますが、追加のリクエストでは「セッションが閉じられました」という結果になります。セッションが使用されるたびに例外が発生します。アプリケーションプールをリセットすることで、別の要求が成功し、さらに「セッションが閉じられました!」ことができます。
動く部分がいくつかありますが、文脈をどのように細かく管理しているのかは分かりません。ここはすべてです! web.configファイルで
:
<property name="current_session_context_class">
NHibernate.Context.WebSessionContext, NHibernate
</property>
(。私は同じ結果で、あまりにも、単に 'ウェブ' に設定しようとしました)
モジュールは、正しく設定されていることが確認さ:
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
Debug.WriteLine("NHibernateSessionModule.Init()");
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.BeginRequest()");
var session = NHibernateHelper.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.EndRequest()");
var session = NHibernateHelper.GetCurrentSession();
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
throw new ApplicationException("Error committing database transaction", ex);
}
finally
{
session.Close();
}
}
CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
}
}
そして、私の小さなヘルパー:
public class NHibernateHelper
{
public static readonly ISessionFactory SessionFactory;
static NHibernateHelper()
{
try
{
Configuration cfg = new Configuration();
cfg.AddAssembly(Assembly.GetCallingAssembly());
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw new ApplicationException("NHibernate initialization failed", ex);
}
}
public static ISession GetCurrentSession()
{
return SessionFactory.GetCurrentSession();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
ありがとうコードです。私は似たようなものを使ってしまった。私はまだ組み込みのWebセッションコンテキストマネージャが動作していないのはなぜか不思議です。コードサンプルの束に使用されています。 – dahlbyk