Skip to content

Instantly share code, notes, and snippets.

@orjan
Created January 25, 2010 10:26
Show Gist options
  • Save orjan/285772 to your computer and use it in GitHub Desktop.
Save orjan/285772 to your computer and use it in GitHub Desktop.
using System;
using System.Web;
using Autofac;
using Autofac.Integration.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Labs2.Dev.Burndown.Data;
using log4net.Config;
using NHibernate;
using NHibernate.Cfg;
namespace Labs2.Dev.Burndown.Web
{
public class Global : HttpApplication, IContainerProviderAccessor
{
private static IContainerProvider containerProvider;
public static ISessionFactory SessionFactory = CreateSessionFactory();
public Global()
{
BeginRequest += delegate { CurrentSession = SessionFactory.OpenSession(); };
EndRequest += delegate
{
if (CurrentSession != null)
CurrentSession.Dispose();
};
}
/// <summary>
/// The main goal is to create only one session per request since the session is the unit of work.
/// Similar to SessionFactory.GetCurrentSession()
/// http://ayende.com/Blog/archive/2009/08/05/do-you-need-a-framework.aspx
/// </summary>
public static ISession CurrentSession
{
get { return (ISession) HttpContext.Current.Items["current.session"]; }
set { HttpContext.Current.Items["current.session"] = value; }
}
#region IContainerProviderAccessor Members
public IContainerProvider ContainerProvider
{
get { return containerProvider; }
}
#endregion
/// <summary>
/// Fluent configuration of the session factory note Mappings(Mapping.GetAutoMappings())
/// </summary>
/// <returns></returns>
private static ISessionFactory CreateSessionFactory()
{
MsSqlConfiguration configuration = MsSqlConfiguration.MsSql2005
.ConnectionString(c => c
.Server("host")
.Database("db-name")
.Username("user")
.Password("pass"));
return Fluently.Configure()
.Database(configuration)
.Mappings(Mapping.GetAutoMappings())
.ExposeConfiguration(SchemaConfiguration)
.BuildSessionFactory();
}
private static IContainerProvider InitializeContainer()
{
var builder = new ContainerBuilder();
builder.Register(c => CurrentSession).As<ISession>();
return new ContainerProvider(builder.Build());
}
// Can be used to export NH config to DB or file
private static void SchemaConfiguration(Configuration obj)
{
}
protected void Application_Start(object sender, EventArgs e)
{
XmlConfigurator.Configure();
containerProvider = InitializeContainer();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment