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:
- Plug in the Autofac HttpHandler for ASP.Net integration by following the instructions here
- Have a singleton instance of the NHibernate session factory (housed in my NHibernateInstance class)
- Have a method on that singleton registered instance that returns an ISession (CreateSession in my example)
- Configure a container scoped instance of the NHibernate ISession, thus ensuring that the created instance will not cross request boundaries
- 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.