28 Jun 2011

Settings.settings vs web.config file with a web service reference

I have a class library called myClassLibrary that contains a reference to a web service.
The web service URL is stored in a Settings.settings file.
This in turn creates an app.config file.

I use myClassLibrary in a web project, and I ran into the problem that the default URL for the web service that I had specified in Settings.settings needed to be different when my web project was in our test environment. So I wanted to be able to override the Settings.settings value with, say, a value in my web.config.

This is how you do it:

Settings.settings


The URL is defined as a value with Scope set to "Application" and a GenerateDefaultValueInCode property set to "TRUE".
This provides a default value when myClassLibrary is run in a non-web context with no override in the app.config file.

app.config


The URL is set in an applicationSettings block to override the default value when the class library is used in a non-web context.

    <applicationSettings>
        <myClassLibrary.Settings>
            <setting name="myWebServiceUrl" serializeAs="String">
                <value>http://whatever.com/myService</value>
            </setting>
        </myClassLibrary.Settings1>
    </applicationSettings>

web.config


Here is where we do the override for use of the class library in a web context.

Firstly we have to define a configuration block that will match the one in app.config:

  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup" >
      <section name="myClassLibrary.Settings" type="System.Configuration.ClientSettingsSection" />
    </sectionGroup>    
  </configSections>

Then we just implement that block with our override value.

  <applicationSettings>
    <myClassLibrary.Settings>
      <setting name="myWebServiceUrl" serializeAs="String">
        <value>http://another.com/myAlternativeService</value>
      </setting>
    </myClassLibrary.Settings>
  </applicationSettings>  

2 comments:

  1. Anonymous3:34 pm

    Thanks for the post! Do you have any idea how the override might be done in a website project using config rather than ?

    ReplyDelete
  2. Anonymous7:14 pm

    THANK YOU! I have been looking for this solution for days!

    ReplyDelete

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!