I'm trying to load a .NET assembly with Reflection (using the Assembly.LoadFrom method), and instantiate some types within this assembly.
This all seems to work fine, but one type I'm trying to instantiate accesses the assembly's configuration within its type initializer: it does ConfigurationManager.GetSection(sectionName). The assembly is then throwing an exception because the configuration section cannot be found.
The config file for the assembly I'm loading is in the same directory, and has the standard name (i.e. AssemblyName.dll.config), and the config definitely has the section being requested. Why can't the configuration section be found? Is there something extra I need to do when loading the assembly?
Because the configuration file being read is the configuration file of the hosting executable. So for example if you are running you code from Foo.exe your config file should be named Foo.exe.config. The AssemblyName.dll.config is never used. If you are running this in a web site then you should use web.config.
You could try using the OpenMappedExeConfiguration method:
var configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "AssemblyName.dll.config";
var section = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None).GetSection(sectionName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With