Search code examples
nhibernatereferencefluent-nhibernatenhibernate-mapping

Fluently map assemblies/entities at run time


Simple question for I bet a not so simple answer.

Think of a project like Wordpress. The base of Wordpress is great and the developers built it to be extended with widgets or plugins etc.

Now think NHibernate, specifically with Fluent Mappings.

Put them together and you have a great and stable "base" system BUT how do you load mappings presented from external assemblies? I realize that the system would have to load the Assemblies on the fly using reflection but how do you configure nHibernate, Fluently, at first run to realize that there are extra entities to be loaded from those assemblies? How do you reference them?

I know you can;t add Mappings at run-time after the configurations is made, well you have to recreate the SessionFactory. This is why I want to load all required entities at runtime.

I also know that this can be somewhat accomplished with Dependancy Injection but I do not wish to go that route nor want the extreme baggage that comes with it.

If the plain old nHiberante config file can be modified and then referenced at runtime to reflect new Entities I can only assume there has to be a way to do it Fluently.

Also, based on answers: do you make the configuration from the base project or a DATA ACCESS assembly?

Thanks for your help.


Solution

  • You can pass an NHibernate Configuration object to Fluently.Configure(). That way you can update the configuration. You need to re-create the session factory when you do that, like you said.

    You can scan the assemblies in the bin folder for assemblies that contain fluent mapping classes (Assembly.Load, then check

    Assembly.GetExportedTypes()
            .Any(x => x.IsClass
                   && !x.IsAbstract
                   && typeof(IMappingProvider).IsAssignabledFrom(type))
    

    or similar) and add the assembly. When all assemblies are scanned, (re-)create the session factory.

    I'm doing something similar in an extensible application framework I have written (although I've moved to from Fluent NHibernate to NHibernate mapping by code, but the principles are similar).