您可以使用 ActionFilter 来执行此操作。这是我用来完全按照您的描述进行的操作。
public class UsingNhibernate : ActionFilterAttribute {
private ISession nhSession;
public override void OnActionExecuting(ActionExecutingContext filterContext) {
nhSession = NHHelper.OpenSession();
nhSession.BeginTransaction();
// set an accessible reference to your nhSession for access from elsewhere
// ((ApplicationController)filterContext.Controller).nHSession = nhSession; is what I do
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
try {
if (filterContext.Exception == null && nhSession != null && nhSession.Transaction.IsActive)
nhSession.Transaction.Commit();
else if (nhSession != null && nhSession.Transaction.IsActive)
nhSession.Transaction.Rollback();
} catch (Exception ex) {
if (nhSession != null && nhSession.Transaction.IsActive)
nhSession.Transaction.Rollback();
nhSession.Dispose();
throw;
}
nhSession.Dispose();
base.OnActionExecuted(filterContext);
}
}
在每个适当的控制器操作(甚至在控制器级别应用到所有操作)上,您只需添加 UsingNhibernate 操作过滤器,如下所示:
[UsingNhibernate]
public ActionResult SaveSystemSetting(SystemAdminVM item) {