Using FluentNHibernate and Rhino-Commons – Part 2

by Rob Kitson

In Using FluentNHibernate and Rhino-Commons – Part 1 I shared how to leverage INHibernateInitializationAware in order to get your FluentNHibernate configuration into the SessionFactory in your UnitOfWork.  In part 2 I’m going to show you how to do the same thing using the latest changes (r328) to FNH.

I was looking at the new FluentNHibernate site earlier and noticed (in the Wiki) that they added a new class called ‘Fluently’ to help assemble the NHibernate configuration.  The first thing that I noticed is that I needed to find a way to get the mappings into the Configuration that I am passing into the FluentNHibernateInitializationAwareConfigurator that I’ve been using.

public class FluentNHibernateInitializationAwareConfigurator : INHibernateInitializationAware  
    public void BeforeInitialization(){}  
    public void Configured(Configuration cfg)  
        Fluently.Configure().Mappings(m =>
                .AlterConventions(convention =>
                        convention.GetForeignKeyName = (prop => prop.Name + "Id");
                        convention.GetForeignKeyNameOfParent = (prop => prop.Name + "Id");
    public void Initialized(Configuration cfg, ISessionFactory sessionFactory){}

This is actually a simplified version of what I am using, which is actually currently leveraging the AutoMapping features against entities in two different assemblies (although the example above is using FluentMapping).  I will probably create my own FluentMappings once the domain gels a bit more so that I can have more granular control over the database structure. 

However I decide to create my mappings (Fluent, Auto, classic HBM files, or a combination) I’ll still be able to use the Fluently class to apply them to the configuration as long as I remember to call Apply() and pass in the NHibernate Configuration that is passed into the Configured() method in my FluentNHibernateInitializationAwareConfigurator.