NHibernate Session Management using FluentNhibernate and Castle Windsor

Time for my first post in a while, thought I would post on session management using Castle Windsor.

I found this good post, http://blog.stevehorn.cc/2009/03/fluent-nhibernate-configured-via.html and I have basically converted it to use Castle for IoC instead.

The Windsor config that will work is below:

var container = new WindsorContainer();
container.AddFacility(); // This adds support to be able to use the UsingFactoryMethod.

container.Register(Component.For().ImplementedBy().LifeStyle.Singleton);
container.Register(Component.For().UsingFactoryMethod(x => x.Resolve() .GetSessionFactory() .OpenSession()).LifeStyle.PerWebRequest);

The only other addition that is needed for Windsor is to add the PerWebRequest module to your Web.config file in the httpModules section:

<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />

And you are done, nice and simple NHibernate Session management using a Windsor container.



Cheers Stefan

No Comments