We can extend the concepts of the previous recipe to NHibernate transactions as well. In this recipe, I'll show you how to create an action filter to manage our NHibernate sessions and transactions.
NeedsPersistenceAttribute
class as shown on the following lines of code:[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public class NeedsPersistenceAttribute : NHibernateSessionAttribute { protected ISession session { get { return sessionFactory.GetCurrentSession(); } } public override void OnActionExecuting( ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); session.BeginTransaction(); } public override void OnActionExecuted( ActionExecutedContext filterContext) { var tx = session.Transaction; if (tx != null && tx.IsActive) session.Transaction.Commit(); base.OnActionExecuted(filterContext); } }
[NeedsPersistence] public ActionResult Index() { return View(DataAccessLayer.GetBooks()); }
DataAccessLayer.GetBooks()
method to use the following code:var session = MvcApplication.SessionFactory .GetCurrentSession(); var books = session.QueryOver<Eg.Core.Book>() .List(); return books;
Before ASP.NET MVC executes the controller action, our NeedsPersistence
action filter starts a new session and NHibernate transaction. If everything goes as planned, as soon as the action is completed, the filter commits the transaction. If the controller action rolls back the transaction, no action is taken.
Notice that we no longer need to use a transaction in our data access layer, as the entire controller action is wrapped in a transaction.