現在,我的會話工廠住在我的控制器,並且一遍又一遍地被創建。我如何創建一個在控制器之間共享的控件?NHibernate 3.0單SessionFactory
public class AccountsController : Controller
{
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(
c => c.FromConnectionStringWithKey("DashboardModels")
))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Accounts>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Notes>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Sales_Forecast>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ChangeLog>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Tasks>())
.BuildSessionFactory();
}
ISessionFactory sessionFactory = CreateSessionFactory();
...
...
編輯我已經添加了SessionController類,像這樣:
public class SessionController : Controller
{
public HttpSessionStateBase HttpSession
{
get { return base.Session; }
}
public new ISession Session { get; set; }
}
,並創建了一個新的SessionFactory實用
類public class NHibernateActionFilter : ActionFilterAttribute
{
private static readonly ISessionFactory sessionFactory = BuildSessionFactory();
private static ISessionFactory BuildSessionFactory()
{
return new Configuration()
.Configure()
.BuildSessionFactory();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var sessionController = filterContext.Controller as SessionController;
if (sessionController == null)
return;
sessionController.Session = sessionFactory.OpenSession();
sessionController.Session.BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var sessionController = filterContext.Controller as SessionController;
if (sessionController == null)
return;
using (var session = sessionController.Session)
{
if (session == null)
return;
if (!session.Transaction.IsActive)
return;
if (filterContext.Exception != null)
session.Transaction.Rollback();
else
session.Transaction.Commit();
}
}
}
Quesions /關注:使用FluentNhibernate,應該如何我配置新的SessionFactory類,以及如何在控制器中創建和使用事務?
http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions – dotjoe
您需要使工廠靜態,但請查看該鏈接以查看如何在事務中包裝每個動作。 – dotjoe
該帖子引用了SessionController類型,我可以在哪裏找到它? – Chazt3n