Refactoring toward frictionless & odorless codeThe baseline
Originally posted at 3/30/2011
This is part of an exercise that I give in my course. The context is an MVC3 ASP.Net application. Here is how we start things:
public class MvcApplication : System.Web.HttpApplication { private static readonly ISessionFactory sessionFactory = BuildSessionFactory(); public static ISession CurrentSession { get{ return HttpContext.Current.Items["NHibernateSession"] as ISession;} set { HttpContext.Current.Items["NHibernateSession"] = value; } } public MvcApplication() { BeginRequest += (sender, args) => { CurrentSession = sessionFactory.OpenSession(); }; EndRequest += (o, eventArgs) => { var session = CurrentSession; if (session != null) { session.Dispose(); } }; } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } private static ISessionFactory BuildSessionFactory() { return new Configuration() .Configure() .BuildSessionFactory(); } }
And in the controller, we have something like this:
public class HomeController : SessionController { public ActionResult Blog(int id) { var blog = MvcApplication.CurrentSession.Get<Blog>(id); return Json(blog, JsonRequestBehavior.AllowGet); } }
This code is valid, it works, it follows best practices and I actually recommend using something very similar here.
It also annoyed me when I wrote it now, enough to write a series of blog posts detailing how to fix this.
More posts in "Refactoring toward frictionless & odorless code" series:
- (12 Apr 2011) What about transactions?
- (11 Apr 2011) Getting rid of globals
- (10 Apr 2011) The case for the view model
- (09 Apr 2011) A broken home (controller)
- (08 Apr 2011) Limiting session scope
- (07 Apr 2011) Hiding global state
- (06 Apr 2011) The baseline

Comments
Comment preview