【发布时间】:2011-04-24 02:09:27
【问题描述】:
我正在使用 ASP.NET MVC 2 编写一个 Web 应用程序,并选择 NHibernate 作为我的 ORM。我基本上是从观看 NHibernate 之夏系列中学到的基础知识,并根据请求策略采用了作者会话来管理会话(第 13 集)。事情似乎运作良好,但我担心这是否是管理会话和线程安全的功能性现实世界方法。如果不是,那么我愿意接受其他示例。
我已添加代码进行详细说明。 这是我设置 SessionFactory 的代码:
public class NHibernateSessionManager
{
public static readonly ISessionFactory SessionFactory;
static NHibernateSessionManager()
{
try
{
Configuration cfg = new Configuration();
if (SessionFactory != null)
throw new Exception("trying to init SessionFactory twice!");
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
throw new Exception("NHibernate initialization failed", ex);
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
这是我让网络请求开始和停止事务的地方:
public class NHibernateSessionPerRequestModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest +=new EventHandler(Application_BeginRequest);
context.EndRequest +=new EventHandler(Application_EndRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
ISession session = NHibernateSessionManager.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
private void Application_EndRequest(object sender, EventArgs e)
{
ISession session = CurrentSessionContext.Unbind(NHibernateSessionManager.SessionFactory);
if(session != null)
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
}
finally
{
session.Close();
}
}
}
这就是我如何从会话工厂中为我的控制器类中的一个存储库获取会话:
CompanyRepository _companyRepository = new CompanyRepository(NHibernateSessionManager.SessionFactory.GetCurrentSession());
【问题讨论】:
标签: asp.net-mvc nhibernate session