Basic NHibernate session management with Autofac

Using the container scoping capablity of Autofac makes NHibernate session management a breeze. Obviously this only handles the most basic session-per-request scenario but we know that can cover a large percentage of most peoples requirements anyway. I am sure other containers could get to this functionality as well, but I was blown away by how easy it was aith Autofac. Below is my session management configuration:

            builder.Register<NHibernateInstance>().SingletonScoped();
            builder.Register(c => c.Resolve
<NHibernateInstance>().CreateSession()).As<ISession>().ContainerScoped();
            builder.RegisterGeneric(typeof (Repository
<>)).As(typeof (IRepository<>)).ContainerScoped();

So the key points are:

  1. Plug in the Autofac HttpHandler for ASP.Net integration by following the instructions here
  2. Have a singleton instance of the NHibernate session factory (housed in my NHibernateInstance class)
  3. Have a method on that singleton registered instance that returns an ISession (CreateSession in my example)
  4. Configure a container scoped instance of the NHibernate ISession, thus ensuring that the created instance will not cross request boundaries
  5. Have the container dynamically inject the ISession into your IRepository implementation

For more information on container scoping in Autofac for ASP.Net web applications check out the Autofac wiki article.

August 19, 2008 14:11 by steven.burman
E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed