July 16, 2014


Configure dynamic assemblies in Fluent NHibernate

In this blog, I am going to cover few issues which you generally face while using Fluent NHibernate in different scenarios.

First issue occurs when you are working on some platform based application, where you don’t want your configuration related code to be changed at any point of time. Moreover you wanted your code to be hidden and non-accessible, but due to the current architecture of fluent nhibernate there is not much options left.

Second issue is generally faced in case of big and growing applications. In a growing application new projects keep on adding in the solution and you have to support entity creation of these newly added projects. If the project is big, code maintenance also becomes a tedious job.

So, to cater above two issues you have two options –

  1. Change your fluent nhibernate configuration code for any entities related changes.
  2. Create custom configuration in the newly created project and dynamically load assemblies from custom configuration to fluent nhibernate configuration.

I like to choose the second option.

Let’s understand in details how we will load assemblies dynamically using custom configuration. To load assemblies dynamically you have to create a custom configuration section in your newly added project’s config file.

    <section name="DynamicAssemblies" type="ConfigHelper, AssemblyOfConfigHelper, Version=, Culture=neutral, PublicKeyToken=null"/>

      <add name="AssemblyKey1" assemblyname="AssemblyName1" ></add>
      <add name="AssemblyKey2" assemblyname="AssemblyName2" ></add>

Also, you have to write a code to make this custom configuration section understandable by your application. To use custom configuration you have to create few support classes too. Sample available at http://msdn.microsoft.com/en-us/library/vstudio/2tw134k3(v=vs.100).aspx

Now read the custom configuration section to get all the assemblies’ details using the following code.


Finally, you just have to do a few changes in your fluent nhibernate configuration mapping code and the configuration will load the assemblies dynamically to generate the entities in the database.

     .Mappings(m =>
                foreach (var assembly in assemblies)
                    //load each assembly in config file


This custom configuration section can be added in any project in the solution, to load the assemblies dynamically without any code change. Using this approach, we will resolve our both issues. This solution will make our application dynamic as well as provide clean and easily maintainable code.

References –