NHibernate.DuplicateMappingException due to work in constructor

We encountered the following problem: Nhibernate could not configure itself somehow…

NHibernate.DuplicateMappingException

NHibernate.MappingException: Could not compile the mapping document: xxxxxx.hbm.xml

Of course, we checked if we did not accidentily mapped a certain class twice, but we were sure we didn’t. In the end, it turned out NHibernate could load all of the assemblies that we gave it, but the Exception occurred only when SessionFactory was build.

Why did this happen?

When Nhibernate is running its configuration, it is also instantiating all the objects that are mapped. This is fine and this has always been the case.

However..

The problem we had was that one of the objects (PassengerFare) had some work in its default constructor, accessing the SettingRepository; In other words, while Nhibernate still busy configuring, instantiating the PassengerFare, the code wanted to already execute some code (of the yet unmapped / not configured Setting class).

How was it solved?

We removed the work from the default constructor, the same ‘work’ was already there in an Init() method of the PassengerFare class.

How to prevent this in future?

We must take care of the following general rule of thumb; “no work in constructors” (Misko Hevery), Moreover, now that we know about Dependency Injection (DI) and are working with NHibernate, we can redefine this rule as:

Definitely no work in default constructors of Nhibernate mapped classes.”

Can I read more about this?

Sure;
http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/

Hope this helps others who accidentily run into the same problem

Cheers,