我已经实现了一个使用DAOFactory和NHibernate Helper进行会话和事务的服务。下面的代码将非常简单:建筑问题asp.net mvc,nhibernate,城堡
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 /控制台应用程序/ WinForm的。我已经可以在控制台应用程序中使用该服务,但希望先改进它。我想第一个改进是通过城堡注入接口INHibernateHelper和IDAOFactory。但我认为问题在于,NHibernateHelper可能会在NHibernateHelper根据'每个请求的Nhibernate会话'模式运行的asp.net上下文中导致问题。我有一个问题是,这种模式是否由nhibernate配置节(设置current_session_context_class = web)决定,还是我可以通过城堡控制它?
我希望这是有道理的。最终目的是揭露IService。
谢谢。
基督教
到目前为止,我似乎可以使用带有Castle的PerWebRequest。 – cs0815 2010-03-05 11:38:43
您是否可以使用Castle来配置选项2的所有内容? – cs0815 2010-03-09 08:12:03