Skip to content

Instantly share code, notes, and snippets.

@oguzhaneren
Last active August 29, 2015 14:05
Show Gist options
  • Save oguzhaneren/b336146f8a8d1b6d54c9 to your computer and use it in GitHub Desktop.
Save oguzhaneren/b336146f8a8d1b6d54c9 to your computer and use it in GitHub Desktop.
NHibernate Session Management Filter for WebApi
public class NhSessionManagementAttribute : ActionFilterAttribute
{
public NhSessionManagementAttribute()
{
SessionFactory = MvcApplication.SessionFactory;
}
private ISessionFactory SessionFactory { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
session.BeginTransaction();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.GetCurrentSession();
var transaction = session.Transaction;
if (transaction != null && transaction.IsActive)
{
transaction.Commit();
}
session = CurrentSessionContext.Unbind(SessionFactory);
session.Close();
}
}
public class MvcApplication : System.Web.HttpApplication
{
public static ISessionFactory SessionFactory
{
get;
private set;
}
public static Configuration Configuration { get; set; }
protected void Application_Start()
{
SessionFactory= BuildSessionFactory();
}
private ISessionFactory BuildSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("default")).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<TaskMap>())
.ExposeConfiguration(cfg =>
{
cfg.SetInterceptor(new TrackingNumberInterceptor());
cfg.CurrentSessionContext<WebSessionContext>();
Configuration = cfg;
})
.BuildSessionFactory();
}
}
public class CustomApiController
: ApiController
{
protected ISession Session
{
get { return MvcApplication.SessionFactory.GetCurrentSession(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment