问题
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?
回答1:
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.
回答2:
As far as I am aware, configuration sections are only read when they are accessed through GetSection()
. If your module code is the only thing calling ConfigurationManager.GetSection("myModuleConfigSection")
then it probably won't matter, as by this point the assembly has been loaded into the AppDomain
. If that section is being read before your assembly is loaded into the AppDomain
then I would imagine that you'd get an exception thrown.
You could probably append your module path to the private bin path the AppDomain
uses for assembly resolution. By adding an additional path, it allows assemblies not currently loaded to be resolved.
来源:https://stackoverflow.com/questions/4845801/custom-configuration-sections-in-mef-exporting-assemblies