开发者

What is the most convenient way of handling nested config data in .Net?

开发者 https://www.devze.com 2022-12-12 09:32 出处:网络
I often store application config data in an app.config file in the following format: <configuration>

I often store application config data in an app.config file in the following format:

<configuration>
    <appSettings>
        <add key="foo" value="foo value"/>
        <add key="bar" value="bar value"/>
     </appSettings>
</configuration>

This can then be easily accessed at runtime with:

string fooValue = ConfigurationManager.AppSettings["foo"];

However this approach does not seem to allow for handling nested/hierarchichal data or multiple items with the same key, e.g. I want to be able to list a number of config items that specify namespace prefix/uri pairs.

I'm findign the documentation is somewhat confusing so was wondering what the consensus was on the easiest/quickest and most convenient way of dealing with nested applicat开发者_运维知识库ion config data. This is a simple per application/installation configuration - not per user.


I'd recommend defining your own XML schema for such hierarchical settings and serializing it to / deserializing from a configuration file on the disk (separate from app.config/web.config)


Look into section groups: http://www.codeproject.com/KB/aspnet/Managing_Webconfig.aspx

Lets you write custom XML fragments in web.config that your custom handler can parse. That allows you to set up more complex configuration options.


For web apps in the past I've used a key in the machine.config to identify the environment (i.e. QA, UAT, Prod, etc.) and then in the web.config used keys like this:

machine.config

        <add key="server_environment" value="qa"/>

web.config

<configuration>
    <appSettings>
        <add key="qa_foo" value="foo value"/>
        <add key="uat_foo" value="foo value"/>
        <add key="prod_foo" value="foo value"/>
     </appSettings>
</configuration>

I get the server_environment value and pair it with the key I'm looking for - changing the environment is as simple as changing the value in the machine.config. As has been mentioned already, section groups are something you'll probably want to investigate as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消