Skip to content

Instantly share code, notes, and snippets.

@dgomesbr
Created February 9, 2012 20:08
Show Gist options
  • Save dgomesbr/1782745 to your computer and use it in GitHub Desktop.
Save dgomesbr/1782745 to your computer and use it in GitHub Desktop.
NHibernateHttpModule.cs depois do resharper
using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
namespace workshop_httpmodule
{
public class NHibernateHttpModule : IHttpModule
{
public static readonly string NHibernateSessionKey = "NHibernateSession";
private static ISession _session;
private static ISessionFactory _factory;
public void Init(HttpApplication context)
{
// ReSharper disable RedundantDelegateCreation
context.BeginRequest += new EventHandler(context_BeginRequest);
// ReSharper restore RedundantDelegateCreation
// ReSharper disable RedundantDelegateCreation
context.EndRequest += new EventHandler(context_EndRequest);
// ReSharper restore RedundantDelegateCreation
}
public void Dispose()
{
}
public static ISession RecuperarSessao
{
get
{
if (HttpContext.Current == null)
{
if (_session != null)
{
return _session;
}
_session = AbrirSessao();
return _session;
}
HttpContext currentContext = HttpContext.Current;
var session = currentContext.Items[NHibernateSessionKey] as ISession;
if (session == null)
{
session = AbrirSessao();
currentContext.Items[NHibernateSessionKey] = session;
}
return session;
}
}
private void context_BeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
HttpContext context = application.Context;
context.Items[NHibernateSessionKey] = AbrirSessao();
}
private void context_EndRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
HttpContext context = application.Context;
var session = context.Items[NHibernateSessionKey] as ISession;
if (session != null)
{
session.Flush();
session.Close();
}
context.Items[NHibernateSessionKey] = null;
}
private static ISession AbrirSessao()
{
ISession session = GetFactory().OpenSession();
if (session == null)
throw new InvalidOperationException("OpenSession() is null.");
return session;
}
private static ISessionFactory GetFactory()
{
if (_factory == null)
{
var config = new Configuration();
config.Configure();
_factory = config.BuildSessionFactory();
if (_factory == null)
throw new InvalidOperationException("BuildSessionFactory is null.");
}
return _factory;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment