Justin Self
Justin Self

Reputation: 6265

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?

Upvotes: 2

Views: 4587

Answers (2)

Eva423
Eva423

Reputation: 53

As David said in his answer, the configSections section needs to be at the top of the config file.

Here is a link to back it up from Microsoft:

If this element is in a configuration file, it must be the first child element of the element.

So you need to switch around the sections so that it is as follows:

 <?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>

Upvotes: 0

David
David

Reputation: 218827

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.

Upvotes: 4

Related Questions