Fluent Nhibernate and ASP.NET MVC
oktober 31, 2010
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!
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?
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”
[…] opens when the request begins and closes when the request ends. I already blogged about that here. This also how Ayende demonstrates this in the Tekpub series. Global.asax is also the place where […]
Thanks for this post.
This is the only page I have found that talks about just ASP.Net MVC and Fluent NHibernate. All others have other references eg/StructureMap, Castle Windsor etc etc.
Did you ever do a post about dependency injection? I’m trying to understand the merits of DI and see no problem accessing the current session
Yes it would be nice to see a tutorial on how you now can use DI and maybe have a repository.
Very good article!
The answer, in fact, is to write a number of books so that the streams add aas much as something important.