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"> | Configuration config = new Configuration(); config.Properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider, NHibernate"); config.Properties.Add("show_sql", "true"); Fluently.Configure(configuration) _factory = config.BuildSessionFactory(); |