Fluent Nhibernate and ASP.NET MVC

For those of you who follow our personal tweets (yeah we have to tweet more with our @itsletnl account), you probably noticed how we're currently involved (or obsessed) by Fluent Nhibernate. Fluent Nhibernate FTW!

Itslet Fluent Nhibernate

Fluent Nhibernate uses poco mappings instead of XML mapping, like its big brother Nhibernate. There is no strong argument to use Fluent Nhibernate instead of Nhibernate, it is just a matter of taste to me. Although, Fluent Nhibernate can automap and autopersist your entities, based on convention, and Nhibernate cannot.

Getting started with Fluent Nhibernate is very simple. Just read their excellent getting started guide. It doesn't make much sense to repeat that on this website with different entities.

But how do we get started with ASP.NET MVC? How do I connect with the Fluent Nhibernate session gracefully?

Handling sessions

I used the book of Jason Dentler to find out more. The most common pattern in web application is the session-per-request. We open the session when the request begins and close it when it ends.

Nhibernate has a contextual session feature which allows a session to be associated with some application specific scope (unit of work). You need to set the current_session_context_class property in the hibernate-configuration section of web.config. But as we use Fluent Nhibernate, we have to use the 'ExposeConfiguration' method.

Here is my Global.asax.cs. Check out line 45: .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "thread_static"))'.

Now we can refer to that session in our controller, like this:

In the example the person is fetched from the database. But to make the app more production worthy, we would use dependency injection rather than directly access the current session. Also, we would not have exposed our connectionstring like that.
But that is a completely new blogpost.

6 Replies to “Fluent Nhibernate and ASP.NET MVC”

Leave a Reply to Michał Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.