现在,我的会话工厂存在于我的控制器中,并且被一遍又一遍地创建。如何创建一个在控制器之间共享的控制器?
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();
}
}
}
问题/疑虑:使用 FluentNhibernate,我应该如何配置我的新 SessionFactory 类,以及如何在我的控制器中创建和使用事务?