Wednesday, November 24, 2010

Configuration files for .net assembly

.Net windows application or web application have a configuration file where application specific configuration information is stored e.g. windows application stores configuration information in appName.config file and web applications in web.config file.

.Net does not allow having assembly specific configuration file.

The application configuration file is stored in application default app domain. All the binding rules are then followed as per the application configuration file.

It’s possible to specify custom configuration file while creating the app domain. So load your assembly in different app domain and specify the custom configuration file while creating app domain. Read AppDomainSetup class for more information on how to set configuration file.

Directing assembly loader to look for an assembly in specific folder

.Net assembly loader loads assemblies from GACUtil or from private path given in the application configuration file. It cannot load assemblies from any other folder than what is specified in application configuration file. In some cases, it’s not possible to modify application configuration file e.g. plug-in (add-on) architecture. Plug-in vendor writes a plug-in (or add-on) which is nothing but a library implementing certain well known interfaces. Generally, the plug-in binaries are deployed in the dedicated folder as specified given by the application vendor.

If the plug-in binary requires certain assemblies to be loaded from a well known path then it cannot just change the application configuration file as the configuration file is not owned by plug-in and it’s inappropriate to change loading application configuration file. Another way to modify private path is to change it using AppDomain class. The plug-in library gets loaded in some appdomain (either dedicated or default). AppendPrivatePath method of the appdomain class can be used to append your own path in the private path of the application. This way the plug-in dependant binaries will get loaded in the application. As per Microsoft AppendPrivatePath method is obsolete and may not be available in future versions of .net. It’s available in .net version 2.0, 3.0, 3.5 and 4.0. Microsoft recommends AppDomainSetup class instead. The object of this class can be passed to the AppDomain::Create method. The problem with this approach is you will have to create separate appdomain otherwise it will not work. Sometimes it’s not possible to create separate AppDomain e.g. if you are created UI controls then it’s not possible to pass UI control objects across appdomain.

Another way to achieve this is to register the dependant assemblies in GAC. The loader first searches GAC for any dependant assembly and then private path. But deploying assemblies in GAC is discouraged if it’s not shared between multiple applications as it violates .net principle of xcopy install.