我已经实现了一个使用 DAOFactory 和 NHibernate Helper 进行会话和事务的服务。以下代码非常简化:
public interface IService
{
IList<Disease> getDiseases();
}
public class Service : IService
{
private INHibernateHelper NHibernateHelper;
private IDAOFactory DAOFactory;
public Service(INHibernateHelper NHibernateHelper, IDAOFactory DAOFactory)
{
this.NHibernateHelper = NHibernateHelper;
this.DAOFactory = DAOFactory;
}
public IList<Disease> getDiseases()
{
return DAOFactory.getDiseaseDAO().FindAll();
}
}
public class NHibernateHelper : INHibernateHelper
{
private static ISessionFactory sessionFactory;
/// <summary>
/// SessionFactory is static because it is expensive to create and is therefore at application scope.
/// The property exists to provide 'instantiate on first use' behaviour.
/// </summary>
private static ISessionFactory SessionFactory
{
get
{
if (sessionFactory == null)
{
try
{
sessionFactory = new Configuration().Configure().AddAssembly("Bla").BuildSessionFactory();
}
catch (Exception e)
{
throw new Exception("NHibernate initialization failed.", e);
}
}
return sessionFactory;
}
}
public static ISession GetCurrentSession()
{
if (!CurrentSessionContext.HasBind(SessionFactory))
{
CurrentSessionContext.Bind(SessionFactory.OpenSession());
}
return SessionFactory.GetCurrentSession();
}
public static void DisposeSession()
{
var session = GetCurrentSession();
session.Close();
session.Dispose();
}
public static void BeginTransaction()
{
GetCurrentSession().BeginTransaction();
}
public static void CommitTransaction()
{
var session = GetCurrentSession();
if (session.Transaction.IsActive)
session.Transaction.Commit();
}
public static void RollbackTransaction()
{
var session = GetCurrentSession();
if (session.Transaction.IsActive)
session.Transaction.Rollback();
}
}
归根结底,我只想将 IService 公开给 ASP.NET MVC/Console 应用程序/Winform。我已经可以在控制台应用程序中使用该服务,但想先对其进行改进。我想第一个改进是通过城堡注入接口 INHibernateHelper 和 IDAOFactory 。但我认为问题在于 NHibernateHelper 可能会在 asp.net 上下文中导致问题,其中 NHibernateHelper 应该根据“每个请求的休眠会话”模式运行。我的一个问题是这种模式是否由 nhibernate 配置部分(设置 current_session_context_class = web)决定,还是我可以通过城堡以某种方式控制它?
我希望这是有道理的。最终目的只是公开 THE IService。
谢谢。
基督教