Saturday, February 20, 2010

No configuration file with NHibernate

Note: This post is based on NHibernate version 2.1 with Fluent NHibernate version 1.0 RTM.

In my previous post about Fluent NHibernate, I explained how to use Fluent NHibernate to replace your NHibernate mapping files (.hbm.config) with c# code. In this post I'll show you how to also replace the  NHibernate configuation file (.cfg.xml) with code.

This time you don't need to add references to any special library. Converting the config file to code is very, very easy. The config file is made up of a bunch of dictionary entries where each entry has a key (the NHibernate setting name) and a value (the actual value for that setting). The NHibernate has a configuration API that works the same way. So you can just take out the line that loads your config file (config.Configure("PocoLib.cfg.xml");) with a series of calls config.Properties.Add().

Before (with a .cfg.xml file) After (with code)

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">
      NHibernate.Connection.DriverConnectionProvider
    </property>
    <property name="connection.driver_class">
      NHibernate.Driver.SqlClientDriver
    </property>
    <property name="connection.connection_string">
      Server=xp-octosql;database=PocoLib;Integrated Security=SSPI;
    </property>
    <property name="dialect">
      NHibernate.Dialect.MsSql2005Dialect
    </property>
    <property name="show_sql">
      true
    </property>
    <property name='proxyfactory.factory_class'>
      NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
    </property>
    <property name="adonet.batch_size">16</property>
  </session-factory>
</hibernate-configuration>

Configuration config = new Configuration();

config.Properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider, NHibernate");

config.Properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");

config.Properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");

config.Properties.Add("connection.connection_string", "Server=xp-octosql;database=PocoLib;Integrated Security=SSPI;");

config.Properties.Add("show_sql", "true");

config.Properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu");

config.Properties.Add("adonet.batch_size", "16");

  Fluently.Configure(configuration)
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerCRUDTests>())
        .BuildConfiguration();

_factory = config.BuildSessionFactory();