Skip to content

Instantly share code, notes, and snippets.

@hahmed
Created September 27, 2012 07:55
Show Gist options
  • Select an option

  • Save hahmed/3792754 to your computer and use it in GitHub Desktop.

Select an option

Save hahmed/3792754 to your computer and use it in GitHub Desktop.
nhibernate session
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Application["NHSessionFactory"] = CreateSessionFactory();
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(ConfigurationManager.AppSettings["ConnectionString"]))
.Mappings(m => m.AutoMappings.Add(CreateAutomappings))
.BuildSessionFactory();
}
private static AutoPersistenceModel CreateAutomappings()
{
return AutoMap
.AssemblyOf<AutomappingConfiguration>(new AutomappingConfiguration())
.Override<User>(u => u.Table("tUser"));
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
ISessionFactory sessionFactory = (ISessionFactory) Application["NHSessionFactory"];
Context.Items["NHSession"] = sessionFactory.OpenSession();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
ISession session = (ISession) Context.Items["NHSession"];
session.Dispose();
}
protected void Application_End(object sender, EventArgs e)
{
ISessionFactory sessionFactory = (ISessionFactory)Application["NHSessionFactory"];
sessionFactory.Dispose();
}
}
public class TransactionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
DependencyResolver.Current.GetService<ISession>().BeginTransaction(IsolationLevel.ReadCommitted);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ITransaction currentTransaction = DependencyResolver.Current.GetService<ISession>().Transaction;
if (currentTransaction.IsActive)
{
if (filterContext.Exception != null && filterContext.ExceptionHandled)
{
currentTransaction.Rollback();
}
}
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
ITransaction currentTransaction = DependencyResolver.Current.GetService<ISession>().Transaction;
base.OnResultExecuted(filterContext);
try
{
if (currentTransaction.IsActive)
{
if (filterContext.Exception != null && !filterContext.ExceptionHandled)
{
currentTransaction.Rollback();
}
else
{
currentTransaction.Commit();
}
}
}
finally
{
currentTransaction.Dispose();
}
}
}
@hahmed
Copy link
Author

hahmed commented Sep 27, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment