In one of my recent projects using ASP.NET MVC (updated to RC2) I was going to use Fluent NHibernate. While using Fluent NHibernate I also needed Castles NHibernate Facility for session management, which would simplify the management of sessions in the repositories in the project. It wasn't as easy as I'd hoped to get it all running smoothly.

EDIT: I’d recommend you to use Sharp Architecture (http://code.google.com/p/sharp-architecture/) which is a project template complete with nhibernate+automap, castle windsor and a bunch of other useful things.

1. Castle binaries

First off, get the latest (trunk) Castle binaries from their build server (or build it yourself). You'll need something later than RC3 (which is the version that's available for download as a release) since the IConfigurationBuilder wasn't public before and there was no way of defining a custom configuration builder which we will leverage to be able to hook into the configuration and making sure that automappings are used.

2. Create custom configuration builder

Based upon this excellent post by Mike Hadlow we're creating a custom configuration builder. This is where the magic from Fluent NHibernate comes into play as well.

   1: public class FluentNHibernateConfigurationBuilder : IConfigurationBuilder
   2: {
   3:     public NHibernate.Cfg.Configuration GetConfiguration(IConfiguration facilityConfiguration)
   4:     {
   5:         var defaultBuilder = new DefaultConfigurationBuilder();
   6:         var configuration = defaultBuilder.GetConfiguration(facilityConfiguration);
   7:         
   8:         configuration.AddAutoMappings(AutoPersistenceModel.MapEntitiesFromAssemblyOf<Headline>());
   9:  
  10:         return configuration;            
  11:     }
  12: }

The method AddAutoMappings() on line 8 does all the magic, it's an extension method from Fluent NHibernate which will wire up the normal automappings from Fluent NHibernate. If you want to use the normal Fluent Nhibernate way with manually mapping entities there's a method called AddMappingsFromAssembly() which you should use instead.

3. Setup HttpModule for Castle NHibernate integration

Since we're using Castle NHibernate facility in a web environment we're going to use their httpmodule for managing sessions as well. If you don't manually set it up correctly you will run into issues like "no session or session was closed" with lazy loading when the session is closed. For example if the view is iterating over a list of objects which are supposed to be lazy loaded. With this HttpModule it will take care of it and setup a session per request.

The <httpModules> section of the web.config looks like this with the addition of the new NHibernateSessionWebModule:

<httpModules>
      <add name="ScriptModule" 
           type="System.Web.Handlers.ScriptModule,
                 System.Web.Extensions,
                 Version=3.5.0.0,
                 Culture=neutral,
                 PublicKeyToken=31BF3856AD364E35"
       />
       <add name="UrlRoutingModule" 
            type="System.Web.Routing.UrlRoutingModule,
                  System.Web.Routing,
                  Version=3.5.0.0,
                  Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35"
       />
       <add name="NHibernateSessionWebModule" 
            type="Castle.Facilities.NHibernateIntegration.Components.SessionWebModule,
                  Castle.Facilities.NHibernateIntegration"
       />
</httpModules>

4. Initialize the container

Do something like this in the Application_Start in your HttpApplication class (usually global.asax.cs). The line number 7 sets the controller factory from the mvccontrib project as the default. This means that the controllers will be resolved by castle windsor and all dependencies will also be resolved from the container.

   1: IWindsorContainer container = new WindsorContainer();
   2:  
   3: // Configure the container either by the ordinary config file with XmlInterpreter
   4: // or by fluent like this etc
   5: container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>());
   6:  
   7: ControllerBuilder.Current.SetControllerFactory(new MvcContrib.Castle.WindsorControllerFactory(Container)); 

5. Configure Windsor/NHibernate Facility in web.config

First off we add a new <section> to <configSections> in web.config.

<section
  name="castle"
  type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />

The <castle> section  is quite large but we'll break it down.

   1: <castle>
   2:   <facilities>
   3:     <facility id="nhibernate"
   4:               isWeb="true"
   5:               type="Castle.Facilities.NHibernateIntegration.NHibernateFacility,
   6:                     Castle.Facilities.NHibernateIntegration"
   7: configurationBuilder="Incendi.Configuration.FluentNHibernateConfigurationBuilder, Incendi">
   8:         
   9:       <factory id="nhibernate.factory" >
  10:         <settings>
  11:           <item key="show_sql">true</item>
  12:           <item key="connection.provider">NHibernate.Connection.DriverConnectionProvider</item>
  13:           <item key="connection.driver_class">NHibernate.Driver.SqlClientDriver</item>
  14:           <item key="dialect">NHibernate.Dialect.MsSql2005Dialect</item>
  15:           <item key="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=Incendi;Integrated Security=True</item>
  16:           <item key="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</item>
  17:         </settings>
  18:       </factory>
  19:         
  20:     </facility>
  21:   </facilities>
  22:   <components>
  23:     <component id="GenericRepository" type="Incendi.Repositories.Repository`1, Incendi"/>
  24:   </components>
  25: </castle>


On line 4 we tell NHibernate Facility that we'll we using it in a web environment so it can use a special sessionstore for this purpose. Line number 7 indicates that we are specifying a custom configuration builder, which is the one we created in step 2. Make sure the namespace.class, assembly is correct. If you miss this you'll get a not so informative error "classType must be set". Next is the factory where we specify the configuration (if you want some in web.config, in my case I needed the type and connectionstring in the web.config and not specified by Fluent NHibernate since I switch it to SQLite when testing.

Note: I had to add line number 16 after upgrading NHibernate to 2.1

As you can see in the <components> section I've also registered a "GenericRepository" class. This is my base generic repository Repository<T>. There are lots of generic repositories out there, look at Rhino.Commons for example. It's quite easy to write one on your own as well.

6. Using SessionManager from NHibernate Facility in the repository

By setting up NHibernate Facility and retrieving the repository from Windsor which will inject the SessionManager into the Repository. It's now just as easy as calling OpenSession() on SessionManager to get a session. Below is an excerpt from the generic repository I wrote and use in the application to show you how easy it is when you don't need to worry about session management.

   1: public class Repository<T>
   2: {
   3:     private readonly ISessionManager _sessionManager;
   4:  
   5:     public Repository(ISessionManager sessionManager)
   6:     {
   7:         _sessionManager = sessionManager;
   8:     }
   9:  
  10:     public virtual IList<T> GetAll()
  11:     {
  12:         using (var session = SessionManager.OpenSession())
  13:         {
  14:             return session.CreateCriteria(typeof(T)).List<T>();
  15:         }
  16:     }
  17:  
  18:     public virtual T Get(int id)
  19:     {
  20:         using (var session = SessionManager.OpenSession())
  21:         {
  22:             return session.Get<T>(id);
  23:         }
  24:     }
  25: }

 

7. Putting all of it to use with the controllers

For example, I’ve added a UserService component to the castle windsor container which implements IUserservice. The UserController requires a IUserService in the constructor. This dependency will be resolved by castle windsor automatically thanks to the controller factory.

   1: public class UserController : Controller {
   2:     private readonly IUserService _userService;
   3:  
   4:     public UserController(IUserService userService) {
   5:         _userService = userService;
   6:     }
   7: }

Phew, that's a lot of configuration to get it up and running. I hope I didn't forgot anything, drop me a comment if you're having trouble setting it up. Good luck!


blog comments powered by Disqus