これを行うには、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) {