Custom Configuration Sections in MEF Export Assemblies

I have an assembly that contains classes that import several classes from different assemblies that are not referenced at compile time, but they are detected at runtime through the directory. Exporting classes want to define custom configuration sections for the configuration file in the host application of the importing assembly. However, since the importing host host application does not know the exporting assemblies at compile time, it cannot load the assembly to use custom section handler implementations in them.

One of the ways I came across is to put the export assemblies in the same folder as the assembly of the import host node. But I would like to allow other developers to configure any folder in which they want to store their assemblies for export.

One thing I can do is copy the contents of the configured developer folder to the host folder at startup. But I would prefer to avoid these extra moving parts and code in order to support if I can. Is there a better way around this? Is there a way to point the application to additional directories when looking for assemblies that define custom configuration sections?

+6
source share
2 answers

I ran into the same problem using StructureMap to dynamically find assemblies. It seems that the ConfigurationManager is only looking for the specified assembly for ConfigurationSection in the Bin-Folder and GAC. It does not seem to work even if the assembly is loaded into the current AppDomain.

But the fact that the ConfigurationSection assembly is already loaded can be used for a simple workaround:

AppDomain.CurrentDomain.AssemblyResolve += (o, args) => { var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); return loadedAssemblies.FirstOrDefault(asm => asm.FullName == args.Name); }; 

AssemblyResolve-Event is fired whenever the CLR cannot find a specific assembly. Just register the callback before the first call to GetSection ().

It works for me.

+6
source

As far as I know, configuration sections are only read when they are accessible through GetSection() . If your module code is the only thing that calls ConfigurationManager.GetSection("myModuleConfigSection") , then this probably does not matter, since at this point the assembly was loaded into the AppDomain . If this section is read before your assembly is loaded into the AppDomain , then I would suggest that you get an exception.

Perhaps you can add the module path to a separate database path that AppDomain uses to resolve the assembly. By adding an additional path, it allows an assembly that is not currently loading.

0
source

All Articles