我已經實現了一個使用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