Skip to content

Instantly share code, notes, and snippets.

@Itslet
Created October 31, 2010 08:47
Show Gist options
  • Save Itslet/656311 to your computer and use it in GitHub Desktop.
Save Itslet/656311 to your computer and use it in GitHub Desktop.
Fluent Nhibernate session per request
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Context;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using FeestBeest.Core.Entities;
namespace FeestBeest.Web
{
public class MvcApplication : System.Web.HttpApplication
{
public static ISessionFactory SessionFactory { get; private set; }
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Person", action = "Create", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
SessionFactory = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.
ConnectionString(@"Data Source=My2008SQLServer;Initial Catalog=FeestBeest;
Persist Security Info=True;User ID=sa;Password=sa")).Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Person>())
.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
.BuildSessionFactory();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var session = CurrentSessionContext.Unbind(SessionFactory);
session.Dispose();
}
}
}
@ydang204
Copy link

how do i call session after bind it into CurrentSessionContext?

@mxmissile
Copy link

mxmissile commented Aug 7, 2020

var session = sessionFactory.GetCurrentSession();

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