I have an assembly that contains classes that import a number of classes from different assemblies that are not referenced at compile time but are discovered at runtime via a directory catalog. The exporting classes want to define custom configuration sections for the config file in the importing assembly's host application. However, because the importing assembly's host application does not know the exporting assemblies at compile time, it cannot load the assembly to use the custom section handler implementations in them.
One way I have found to work around this is to put the exporting assemblies in the same folder as the importing assembly's host application assembly. But I would like to allow other developers to configure any folder they want to hold their exporting assemblies.
One thing I can do is copy the contents of the developer's configured folder to the host's folder on startup. But I'd rather avoid those extra moving parts and code to maintain if I can. Is there a better way around this? Is there a way to point an application to additional directories when looking for assemblies that define custom config sections?
I ran into the same problem while using StructureMap to discover Assemblies dynamically. The ConfigurationManager seems to look for the specified Assembly for the ConfigurationSection only in the Bin-Folder and the GAC. It doesn't seem to work even if the Assembly was loaded into the current AppDomain.
But the fact, that the ConfigurationSection's 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);
};
The AssemblyResolve-Event is fired whenever the CLR cannot find a certain Assembly. Just ensure to register the callback before the first call to GetSection().
Works for me.