现在,我的 session 工厂存在于我的 Controller 中,并且被一遍又一遍地创建。如何创建一个在 Controller 之间共享的 Controller ?
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 Utility Class
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 类,以及如何在我的 Controller 中创建和使用事务?
最佳答案
您需要将 SessionFactory 设为静态,以便所有 Controller 都使用相同的实例。 Ayende 有一个 good blog post有关如何执行此操作以及如何将操作包装在事务中的示例。
public class SessionController : Controller
{
public HttpSessionStateBase HttpSession { get { return base.Session; } }
public new ISession Session { get; set; }
}
//you could put this class in the same physical file as the SessionController.cs
//since they are tightly coupled to each other
public class NHibernateActionFilter : ActionFilterAttribute
....
然后将您的 AccountController 更改为...
public class AccountsController : SessionController
{
public ActionResult Index()
{
//Session is primed and ready for use
}
}
最后确保在 global.asax 中注册 Action 过滤器
关于asp.net-mvc-3 - NHibernate 3.0 单 SessionFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631023/