Wednesday, October 19, 2005

NHibernate Tricks: Locating the Mapping Files

The various examples I’ve seen of NHibernate all had the mapping files (*.hbm.xml) in the same location as the business entities (BEs) they map.

That kind of sucks for trying to abstract out your data access.  Storage-specific stuff shouldn’t be co-located with your BEs, it should be in a storage-specific project.  Like a Data Access Layer project.

No problem.  Create or move your map files in your DAL project.  Make sure the map files are embedded resources, not content.  (Check the “Build Action” field in the file’s properties.)  Ensure the DAL project references NHibernate.dll — but you figured that out already since you’d have had beaucoup problemos with your “using” statements, so why am I beating a dead horse?

Now mod the constructor of the class you’re using to do all your data access, adding in a statement to add the DAL assembly to NHibernate’s Configuration.  Here’s what I’ve got for my PersonTypeDA class:

public PersonTypeDA()

{

   Configuration cfg = new Configuration();

   cfg.AddAssembly("nUGSoft.DAL");

   factory = cfg.BuildSessionFactory();

}

You’re now telling NHibernate to look at the current assembly where you’ve embedded the mapping files for your BEs.  The single statement cfg.AddAssembly("nUGSoft.DAL");  loads all maps in the assembly, so you don’t need to worry about trying to keep straight which BEs are referencing which others are referencing which others are referencing which others… Nevermind.  You get the picture.

Poof!  Everything’s happy, and you’ve got your persistence-specific stuff separated out where it belongs.

Shiny.

Now Playing: Neutral Milk Hotel — In the Aeroplane Over The Sea Nifty stuff with lots of very different musical instruments (flugelhorns!), odd lyrics.  Lots of fun.  I told James it was kind of like goat meat.  Interesting once, but I’m not sure how often I’ll eat it.  Wait, that was either Rage Against The Machine or System of a Down.  Nevermind.  But it was a cool analogy all the same.

1 comment:

Anonymous said...

Useful, thank you.

Subscribe (RSS)

The Leadership Journey