Refactoring toward frictionless & odorless code: The baseline
Join the DZone community and get the full member experience.
Join For Freepublic 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.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments