Locating NHibernate Mapping Files

I have an assembly full of data objects (say, MyGreatApp.Objects.dll), and an assembly that manages data access (say, MyGreatApp.DataAccess.dll). As the data access DLL is handling persistence, it should have the embedded NHibernate mapping files (*.hbm.xml). I tried to configure a session factory from MyGreatApp.DataAccess.dll like this:

Configuration config = new Configuration();
config.AddClass(typeof(MyGreatApp.Objects.Widget));
SessionFactory = config.BuildSessionFactory();

I thought this would search the current assembly for the Widget.hbm.xml file, and possible the assembly containing the referenced type as well. I was quickly proved wrong as it threw NHibernate.MappingException: Resource not found. NHibernate is only looking for the Widget mapping file in the same place as the type itself, which is MyGreatApp.Objects.dll. Instead we just need to explicitly add the assembly that contains the embedded mapping files:

Configuration config = new Configuration();
config.AddAssembly("MyGreatApp.DataAccess");
SessionFactory = config.BuildSessionFactory();

And this works great! I noticed Jim Holmes is years ahead of me here, but I didn’t have much Google-luck with my initial choice of keywords and so thought I’d post my experience.

Comments