Search code examples
c#.netapp-config

Using ConnectionStrings and custom ConfigSections in the same App.Config


I have a custom configSection that works as expected. However, when I add a 'connectionStrings' section, I receive error:

Configuration system failed to initialize

on line:

StencilObjects so = ConfigurationManager.GetSection( "stencilObjects" ) as StencilObjects;

Here is the config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="connection" connectionString="foo"/>
  </connectionStrings>
  <configSections>
    <section name="stencilObjects" type="Stencil.Configuration.StencilObjects, Stencil.Configuration"/>
  </configSections>
  <stencilObjects>
    <tableData>
      <table schema="Auth" name="SecurityQuestion" />
    </tableData>
  </stencilObjects>
</configuration>

Is there any limitation when using a custom config section? Does this not allow the use of connectionstrings?

Again, when I remove the connectionStrings, the app runs as expected.

Any idea on what is going on?


Solution

  • I haven't found a link to back this up yet with an explicit statement, but I've always used configSections at the top of the file without any problems. Try like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="stencilObjects" type="Stencil.Configuration.StencilObjects, Stencil.Configuration"/>
      </configSections>
      <connectionStrings>
        <add name="connection" connectionString="foo"/>
      </connectionStrings>
      <stencilObjects>
        <tableData>
          <table schema="Auth" name="SecurityQuestion" />
        </tableData>
      </stencilObjects>
    </configuration>
    

    configSections definitely doesn't need to be just before the section(s) it describes. connectionStrings can be in between.