Refactoring toward frictionless & odorless code: Limiting session scope
Join the DZone community and get the full member experience.
Join For FreeIn the previous posts, we have looked at how we are going to setup an application using NHibernate. We set it up using:
public MvcApplication() { BeginRequest += (sender, args) => { CurrentSession = sessionFactory.OpenSession(); }; EndRequest += (o, eventArgs) => { var session = CurrentSession; if (session != null) { session.Dispose(); } }; }
But this code is problematic. It is problematic because the session is open for the lifetime of the request. That is a problem, but probably not because of what you think. The #1 reason for issues like Select N+1 is people accessing lazy loaded properties in the views.
One good way of avoiding that is limiting the session scope only to the action, so when rendering the view, the session is not available. Therefor, every attempt to lazy load, will immediately throw. With ASP.Net MVC, this is very easy:
public class NHibernateActionFilter : ActionFilterAttribute { private static readonly ISessionFactory sessionFactory = BuildSessionFactory(); public static ISession CurrentSession { get { return HttpContext.Current.Items["NHibernateSession"] as ISession; } set { HttpContext.Current.Items["NHibernateSession"] = value; } } private static ISessionFactory BuildSessionFactory() { return new Configuration() .Configure() .BuildSessionFactory(); } public override void OnActionExecuting(ActionExecutingContext filterContext) { CurrentSession = sessionFactory.OpenSession(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { var session = CurrentSession; if (session != null) { session.Dispose(); } } }
We need to modify the SessionController as well, so it would now be:
public class SessionController : Controller { public HttpSessionStateBase HttpSession { get { return base.Session; } } public new ISession Session { get { return NHibernateActionFilter.CurrentSession; } } }
Of course, we have broken the HomeController now, but we will discuss how in the next post.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
How Agile Works at Tesla [Video]
-
How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
-
AI and Cybersecurity Protecting Against Emerging Threats
-
Rule-Based Prompts: How To Streamline Error Handling and Boost Team Efficiency With ChatGPT
Comments