reqestごとにasp.netセッションでstandartシナリオを実装します。 私のasp.netモジュール:asp.net Nhibernateセッション管理
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
var session = SessionManager.SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
var session = SessionManager.CurrentSession;
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(SessionManager.SessionFactory);
}
}
私SessionManagerには、スレッドセーフsingletoneです:中
public class SessionManager
{
private readonly ISessionFactory sessionFactory;
public static ISessionFactory SessionFactory
{
get { return Instance.sessionFactory; }
}
private ISessionFactory GetSessionFactory()
{
return sessionFactory;
}
public static ISession OpenSession()
{
return Instance.GetSessionFactory().OpenSession();
}
public static ISession CurrentSession
{
get
{
if (!CurrentSessionContext.HasBind(Instance.GetSessionFactory()))
return null;
return Instance.GetSessionFactory().GetCurrentSession();
}
}
public static SessionManager Instance
{
get
{
return NestedSessionManager.sessionManager;
}
}
private SessionManager()
{
Configuration configuration = new Configuration().Configure();
sessionFactory = configuration.BuildSessionFactory();
}
class NestedSessionManager
{
internal static readonly SessionManager sessionManager =
new SessionManager();
}
}
主なアイデアオープンセッションは、要求の開始、その後SessionManager.CurrentSession;
セッションを通じてセッションを使用しています設定されたコンテキストで保存されます:
<property name="current_session_context_class">web</property>
マイリポジトリ:このリポジトリはモジュールで開かれたセッションを使用していないいくつかの理由により、
public class RepositoryNew<T> : BaseRepository<T>, IDisposable
{
public RepositoryNew()
{
if (NHibernateSession == null)
//Start session for not web version
}
public void Dispose()
{
//flush session for not web version
}
protected override sealed ISession NHibernateSession
{
get
{
return SessionManager.CurrentSession;
}
}
}
使用
protected void Page_Load(object sender, EventArgs e)
{
var repo = new RepositoryNew<Client>()
clients = repo.GetAll();
}
。
はfalseを返します。したがって、私のコードはリクエストで2番目のセッションを開始します。 デバッガで私はSessionManagerを2回instantietedしていることがわかります。 私は2つの異なるISesssion工場を持っていますか? アイデアはまだありませんが何が問題なのですか?私はそれに多くの時間を費やしました。