Custom configuration sections in MEF exporting assemblies

可紊 提交于 2019-12-04 06:39:29

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!