Using FluentNHibernate and Rhino-Commons

by Rob Kitson


Since it's inception, I have been a big fan of FluentNHibernate.  I am also a big fan of Ayende's Rhino-Tools.
A project that I've been working on recently has given me the opportunity to trying to leverage both.  I wanted to use DatabaseTextFixtureBase from Rhino.Commons.ForTesting with FluentNHibernate to work on my integration tests.  The problem that I kept coming up against was the fact that FluentNHibernate works it's magic on the NHibernate configuration in the PersistenceModel class, and getting your hands on the NHibernate configuration once you call DatabaseTestFixtureBase.InitializeNHibernateAndIoC() Rhino.Commons works it's magic privately and you no longer have access to the NHibernate config (or not in a way that I could see).


As it turns out, my last assumption was wrong.  I asked the Rhino-TOols list how I might go about accomplishing this integration and in as simple a response as I could have hoped, I got a 1-word word response from Ayende, "INHibernateInitializationAware" (and honestly, I'm glad that that was all the help that I got.)  It was a simple hint but it made me go back and look at everything all over again and I saw a bunch of stuff that I hadn't looked at before. And now I'm chuckling a bit over his post from this morning about Static vs. Dynamic Dependencies because when I was looking at the implementations of INHibernateInitializationAware that are in Rhino.Commons I didn't find one that helped me understand what it's purpose was (in his words about another class, "there's not a lot happening there").


As it turns out If you register an INHibernateInitializationAware service with the container, it will be picked up by the NHibernateUnitOfWorkTestContext when it calls CreatConfigs().  So that's what I did.

public class FluentNHibernateInitializationAwareConfigurator : INHibernateInitializationAware
{
    public void BeforeInitialization(){}

    public void Configured(Configuration cfg)
    {
        var persistenceModel = new PersistenceModel
                                   {
                                       Conventions =
                                       {
                                           GetForeignKeyName = (prop => prop.Name + "Id"),
                                           GetForeignKeyNameOfParent = (prop => prop.Name + "Id")
                                       }
                                   };
        persistenceModel.addMappingsFromAssembly(typeof(ClickMap).Assembly);
        persistenceModel.Configure(cfg);
    }

    public void Initialized(Configuration cfg, ISessionFactory sessionFactory){}
}