config files - how to avoid clutter?

  • Thread starter Thread starter Marty McDonald
  • Start date Start date
M

Marty McDonald

Many of an app's classes could read the config file. The config file could
contain many elements, and it will be difficult to know which config file
entry belongs to which class. I could adopt a naming scheme for the
elements. But am I limited to using the <appSettings> element for my
settings? It would be good to have elements such as <myClass1Stuff> so that
it's easy to tell which settings go with each class. But whether I put
<myClass1Stuff> in the <configuration> element or the <appSettings> element,
I receive configuration errors. Does anyone have good ideas/suggestions for
keeping the configuration entries manageable? Thanks!
 
Marty,
Go ahead and create a section new sections in the app.config file.

There is a predefined configSections section in the app.config that you use
to define new sections.

Something like:

<configuration>

<configSections>
<section name="myClass1Stuff"
type="System.Configuration.DictionarySectionHandler, System" />
<sectionGroup name="environments">
<section name="production"
type="System.Configuration.SingleTagSectionHandler, System" />
<section name="development"
type="System.Configuration.SingleTagSectionHandler, System" />
</sectionGroup>
</configSections>

<appSettings>
<add key="key1" value="value1" />
<add key="environment" value="production" />
</appSettings>

<myClass1Stuff>
<add key="key1" value="value1" />
</myClass1Stuff>

<environments>
<production value1="xyz" value2="abc" value3="edf" value4="ghi" />
<development value1="xyz" value2="abc" value3="edf" value4="ghi" />
</environments>

</configuration>

If you inherit from DictionarySectionHandler you can easily change the key
or value in your section. I've derived from DictionarySectionHandler to
change key/value to plugin/type in a few of my projects.

I use the above environments section to define each of my environments,
Production, QA, Test, Development. Where each environment points to the
correct database servers, web servers, message queues, printers any 'per
environment' settings. The appSettings/environment setting is used to
identify the current environment in use.

You then need to use System.Configuration.ConfigurationSettings.GetConfig to
get your section, which returns an object based on the type of section
handler defined for that section (usually HashTable, but can be other object
types.

See the following on how to create new sections via the configSections
section.

http://msdn.microsoft.com/library/d...de/html/cpconconfigurationsectionhandlers.asp

and:
http://msdn.microsoft.com/library/d...ref/html/gngrfconfigurationsectionsschema.asp

Also read about the System.Configuration.ConfigurationSettings class and
other classes in the System.Configuration namespace.

Hope this helps
Jay
 
Back
Top