简体   繁体   中英

Overriding keys from machine.config to web.config

I need to move a key from machine.config to web.config. Below is the setting in machine.config.

<commonsettings>
    <setting environment="dev">
      <common>
          <value1>myValue1</value1>
          <value2>myValue2</value2>
          <value3>myValue3</value3>
      </common>
    </setting>
</commonsettings>

I have above mentioned setting defined in machine.config currently ( 3 keys - value1, value2, value3) , and I want to have only value1 declared in web.config.

I declare only value1 setting, but it does not work. The secion just recognizes only value1. I can not access value2, and value3 declared in machine.config

Below is what I did in web.config.

<commonsettings>
    <setting environment="dev">
      <common>
          <value1>myValue1</value1>
      </common>
    </setting>
</commonsettings>

What I want is that web.config performs some inheritance instead of overriding the whole section.

Can somebody please help me resolving this ?

you can do that in your code I assume you are defining the type of the handler in your machine.config:

<configuration>
  <configSections>
      <section name="commonsettings" type="YourConfigSectionHandler, YourLibrary, Version=1.1.0.0"/>
 </configSections>
<!-- More configuration-->
<configuration>

And creating a class of that type inside your app:

public class YourSectionHandler : IConfigurationSectionHandler
{
    public object Create( object parent, object configContext, XmlNode section )
    {
        //your code to handler the configSection
    }
}

If you see the Create method has an argument object parent . It will contains the configuration of the parent config.

I suposse you have only a machine.config and a web.config.

  1. Once the app launches, it will try to parse machine.config/configSection/commonsettings/ ( section should be declared there ) and the Create method will get called with a null parent.
  2. Later your app's config will get parsed,and Create method will get called again. Now, the parent object parameter will hold the value of the previous step parse result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM