TypeLoadException with ConfigurationSection
Here is the problem, the following piece of code is blowing up with a TypeLoadException:
MyConfigSection section = ConfigurationManager.GetSection(“myConfig”) as MyConfigSection; |
Can you guess what the problem is? The issue is with the app.config configuration. The “myConfig” section is a custom section, so it needs to be defined in the <configSections> elements. Here is the configuration that I had
<configSections> <section name="myConfig" type="Demo.MyConfigSection , Demo" /> </configSections> |
The sharp eyed readers already noticed the problem. There is a space between the end of MyConfigSection and the comma. This space renders the type name invalid. The fix is simply to remove the space before the comma.
But, why is it happening? When you ask to get a section from the configuration, you want to get an object back, and not the xml itself (usually). When you define your custom section in app.config, you need to also define the object that will translate this object from the xml to the object that you want.
Because the type name above is not valid, when we asked to get the myConfig section, .Net tried and failed to create the type, and a TypeLoadException was thrown. It is an easy thing to fix, if you realize where the problem is at the first place.
Comments
Comment preview