Accessing Configuration Settings in .NET Class Libraries
This guide explains how to retrieve configuration settings from app.config
or web.config
within a .NET class library. Avoid using the obsolete ConfigurationSettings.AppSettings.Get()
method.
The Preferred Approach (with caveats):
While ConfigurationManager.AppSettings["MySetting"]
is generally recommended, it's not directly accessible from a class library project without additional steps.
The Solution:
To access configuration settings in your class library, follow these steps:
Add a Reference: Add a reference to System.Configuration
in your class library project.
Create a Custom Section Handler: Create a class that inherits from ConfigurationSectionHandler
and overrides its Create
method. This custom handler will allow you to access your configuration section.
Register the Custom Section: Register your custom section within the <configSections>
element in your app.config
or web.config
file.
Example:
Let's assume you want to read a section named "MySettings":
Custom Section Handler (e.g., MySettingsHandler.cs
):
<code class="language-csharp">using System.Configuration; public class MySettingsHandler : ConfigurationSectionHandler { public override object Create(object parent, object configContext, System.Xml.XmlNode section) { var settings = new MySettingsSection(); // Populate settings from the XML node (section) here, based on your config structure. Example below assumes a single string setting. settings.MySetting = section.Attributes["mysetting"]?.Value; return settings; } } // Define a class to hold your settings public class MySettingsSection { public string MySetting { get; set; } }</code>
Configuration File (app.config or web.config):
<code class="language-xml"><configuration> <configSections> <section name="mySettings" type="MySettingsHandler, YourAssemblyName" /> </configSections> <mySettings mysetting="YourSettingValue" /> </configuration></code>
Replace "YourAssemblyName"
with the actual name of your class library assembly.
Accessing the Settings in your Class Library:
<code class="language-csharp">var settings = (MySettingsSection)ConfigurationManager.GetSection("mySettings"); string mySettingValue = settings.MySetting;</code>
This approach allows you to safely and correctly access configuration settings from your .NET class library. Remember to adjust the custom section handler and configuration file to match your specific configuration structure.
The above is the detailed content of How to Read Configuration Settings from app.config or web.config in a .NET Class Library?. For more information, please follow other related articles on the PHP Chinese website!