NHiberate Configuration

One of the things that kind of confused me when I first started with NHibernate was the configuration and session factory etc. With the use of the NHibernate Contrib package the code in the configuration section changes a little.

(btw an excellent book to read is Hibernate in Action by Christian Bauer and Gavin King if you are just starting out with NHibernate – although Hibernate is the java version with NHibernate being the .Net port the Hibernate examples, patterns, help etc are all VERY relevant – you do the same stuff with NHibernate – this was something I didnt realise when I first started out so if your checking out NHibernate then google Hibernate because that will probibly throw up the answer you are looking for 🙂 )

Anyway, back to configuration – when you use the attribute package load the classes mappings use something like the following:

NHibernate.Cfg.Configuration nhConfig = new NHibernate.Cfg.Configuration();

using (Stream s = new MemoryStream())
{
     HbmSerializer.Default.Serialize(s, typeof(Business.Mappings.Team));
     s.Position = 0;
     nhConfig.AddInputStream(s);
}

_nhFactory = nhConfig.BuildSessionFactory();

If you arent using the contrib package and are using xml mapping files then make sure the mapping file is included as a resource in the project and then replace the whole using block with: nhConfig.AddClass(typeof(Business.Mappings.Team));

Here I prefer to load one class at a time rather than the whole assembly because if you havent remembered to include the xml mapping file as a resource then that class map wont be loaded and it wont be obvious why (you’ll be stumped at why something isnt working / isnt saved – so easy to miss) and if there is a problem with a mapping you know exactly where to look – when you load the entire assembly at once you just get told theres an error but it may not tell you where – very hard to fix – when you load them one at a time it will point you straight to the class with the problem 🙂

Another tip here is NOT to call nhConfig.Configure(); If you call this it will go looking for an xml configuration file for the NHibernate settings rather than looking in the App.Config. You dont want any other configuration files to look after (or maybe you do – its up to you) so just let it do its thing and it will look for the nhibernate configuration section in your App.Config 🙂 (just make sure its in there of course)

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: