NHibernate made easy with StructureMap and Fluent NHibernate

Sunday, October 25 2009

A while back I presented a 10 minute lightning talk at the Sydney Alt.Net group on making NHibernate easier with Fluent NHibernate and StructureMap in the context of an ASP.NET MVC app.

I set about putting this together as I've found a large interest in NHibernate from other developers, but there seems to be a bit of a barrier to entry when it comes to the configuration, mapping and patterns around session lifetime. None of these are really hard, but taken on at once can be a mental hurdle.

StructureMap is similar, for most scenarios a simple tool to use, but the number of options for configuring it can turn people away when looking at the documentation.

The premise of my short talk was that using Fluent NHibernate to configure and map NHibernate, and StructureMap to manage the SessionFactory and Session lifetimes makes it an easy stack to work with. Using this in the context of ASP.NET MVC allows you to inject your data access code very easily into your controllers, giving you a nice, loosely coupled architecture.

I’ve been sitting on this post for a little while (so long in fact, that I'm not the first person to blog about it) because I wasn't sure of the best way to document it. In the end I decided that posting the solution, and adding lots of comments was probably the easiest, because you can step through the code inside VS.NET.

So download it here and have a look. Start at the Global.asax.cs and navigate your way through the code from there. If you’d like to run it, there’s a database creation script there, you’ll need to change the connection string inside Web.config.

Bear in mind, this is NOT thorough documentation for NHibernate or Fluent NHibernate. There are a few best practice type things I’ve left out for the sake of simplicity. For starters there’s no error handling or transaction management, and if you want to use NHibernate seriously you need to understand why you map things the way you do, and what N+1 means. What I did try to achieve was demonstrate that the “ugly” initial parts of NHibernate can be made very simple with a little bit of help from a good IoC container and Fluent NHibernate.

Any feedback would be welcome, I am interested in building this out into a bigger sample so I’m open to ideas.