Creating a Transaction ASP.NET MVC action filter

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.

Getting ready

Complete the previous recipe, Creating a Session ASP.NET MVC action filter.

How to do it...

  1. Add the 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);
        }
    
      }
  2. Decorate your controller actions with the attribute as shown in the following lines of code:
    [NeedsPersistence]
    public ActionResult Index()
    {
      return View(DataAccessLayer.GetBooks());
    }
  3. Update the DataAccessLayer.GetBooks() method to use the following code:
    var session = MvcApplication.SessionFactory
      .GetCurrentSession();
    var books = session.QueryOver<Eg.Core.Book>()
      .List();
    return books;
  4. Build and run your application. Again, you will see the following screenshot:
    How to do it...

How it works...

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.

There's more...

This attribute inherits from our session action filter defined in the previous recipe. If you're managing your session differently, such as session-per-request, inherit from ActionFilterAttribute instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.187.210