Creating a session ASP.NET MVC action filter

Often, a unit of work maps neatly on to a single controller action. I'll show you how to create an action filter to manage our NHibernate sessions in an ASP.NET MVC or Web API 2 application.

Getting ready

Follow the instructions in the Getting ready section of the Setting up session-per-web request recipe in the beginning of this chapter. You can name the project ActionFilterExample.

How to do it…

  1. Add the NHibernateSessionAttribute class as shown in the following code:
    [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] public class NHibernateSessionAttribute : ActionFilterAttribute { public NHibernateSessionAttribute() { Order = 100; } protected ISessionFactory sessionFactory { get { return MvcApplication.SessionFactory; ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.