Search code examples
c#asp.net.netconfigurationmanager

"Could not load type x from assembly" Exception When Trying to Get Custom Configuration Section


When I attempt to load a custom configuration section I defined, I receive the "Could not load type x from assembly" exception. After looking at several similar questions, none of the answers worked. I confirmed that I was using the correct fully qualified class name, as well as the correct assembly name. The assembly was located in the same folder as the configuration file that declared the corresponding configuration section. Nevertheless, I still received an error. Here is a simplified version of my code:

namespace MyNamespace 
{
    public class MyClass
    {
        public MyClassConfigurationSection Configuration { get; set; }

        public void LoadConfiguration()
        {
            Configuration = ConfigurationManager.GetSection("mySection") as MyClassConfigurationSection;
        }

        public class MyClassConfigurationSection()
        {
            /* ... /*
        }
    }

Solution

  • The problem turned out to be nesting the custom configuration section class definition inside of another class definition. Apparently, the configuration manager's loading logic cannot instantiate a nested class, even if it is publicly accessible. Simply moving the custom configuration class out of the outer class and into the containing namespace fixed the issue.