In. NET, a method is more convenient to operate configuration items, and. net is more convenient to operate the configuration.
During application development, we often provide some configuration items for the software to allow the software to do things flexibly according to the configuration items, such as configuring the log file path. In addition, we can also use configuration items to store user preference settings.
. NET provides the configuration mechanism and configuration file by default. The app. config or web. config file in the project (if not, you can add it) is the configuration file provided by. NET for us. Under the configuration of the root node in this configuration file, create the deleteworker node. In this node, we can add custom configuration items. The ConfigurationManager class also provides methods for accessing and operating the Configuration file (represented by the Configuration class. Note that this class is in the System. Configuration. dll file and must be added to the reference of the project before it can be used.
This article mainly introduces a more convenient way to access/store configuration items. Of course, it is essentially completed using the ConfigurationManager class. Its main feature isSolve this problem in an object-oriented wayTo be more specific, we create a class that contains some attributes used to represent configuration items. By accessing or setting these attributes, we can obtain or update the corresponding configuration items.
I. Implementation
First, we add an extension method AddOrUpdateAppSettingItem for the Configuration class, as shown below:
/// <Summary> /// add (if not exists) or update (if already exists) to the configured paietings Section) given key and value /// </summary> /// <param name = "config"> </param> /// <param name = "key"> </ param> // <param name = "value"> </param> public static void AddOrUpdateAppSettingItem (this Configuration config, string key, string value) {if (config. appSettings. settings. allKeys. contains (key) {config. appSettings. settings [key]. value = value;} else {config. appSettings. settings. add (key, value );}}}
This method is mainly used to add (the configuration item does not exist) to the appSettings node or update (the configuration item already exists) The configuration. Next we will use this method.
Next, we define the abstract base class ConfigSetting as follows:
Public abstract class ConfigSetting {// <summary> // configuration class /// </summary> /// <param name = "configuration"> configuration </param> public configSetting (Configuration configuration) {Configuration = configuration;} // <summary> /// current Configuration /// </summary> public Configuration {get ;} /// <summary> /// obtain the current program configuration /// </summary> /// <param name = "config"> </param> /// <returns> </returns> public static Co Nfiguration GetCurrentConfiguration () {return ConfigurationManager. openExeConfiguration (ConfigurationUserLevel. none );} /// <summary> /// return the value of the specified configuration item /// </summary> /// <param name = "settingKey"> </param> /// <returns> </returns> protected virtual string GetSettingValue ([CallerMemberName] string settingKey = null) {return Configuration ?. Ettings ?. Settings [settingKey]?. Value ;} /// <summary> /// return the value of the specified configuration item /// </summary> /// <typeparam name = "T"> Value Type </typeparam>/ // <param name = "settingKey"> </param> // <returns> </returns> protected virtual T GetSettingValue <T> ([CallerMemberName] string settingKey = null) {var value = GetSettingValue (settingKey); if (string. isNullOrWhiteSpace (value) {return default (T);} else {return (T) Convert. changeType (value, typeof (T ));}} /// <Summary> /// set the value for the specified configuration item /// </summary> /// <param name = "value"> </param> /// <param name = "settingKey"> </param> protected virtual void SetSettingValue (object value, [CallerMemberName] string settingKey = null) {Configuration. addOrUpdateAppSettingItem (settingKey, value ?. ToString (); Configuration. Save ();}}
It mainly includes a static method and three protected virtual methods, which are described as follows:
1. The static method GetCurrentConfiguration returns the configuration class of the current application;
2. The GetSettingValue and SetSettingValue methods are responsible for reading and setting the values of the specified configuration item respectively;
3. GetSettingValue has two reloads, one of which is used to support generics;
4. The CallerMemberName feature is included in their method signatures. You can use this attribute to obtain the name of the method or attribute that calls this access.
Then, create a class named AppConfigSetting, which includes some attributes that represent configuration items and inherit from ConfigSetting, as shown below:
public class AppConfigSetting : ConfigSetting { public AppConfigSetting(Configuration configuration) : base(configuration) { } public DateTime InstallDateTime { get { return GetSettingValue<DateTime>(); } set { SetSettingValue(value); } } public string LogFileName { get { return GetSettingValue(); } set { SetSettingValue(value); } } public int ReadBlockSize { get { return GetSettingValue<int>(); } set { SetSettingValue(value); } } }
Note:
1. We can see that three attributes are added in it. In their get and set segments, two methods corresponding to the base class are called. For non-string-type configuration items, GetSettingValue <T> is called.
2. Through the CallerMemberName feature we mentioned earlier, we can get the attribute name here and get the corresponding configuration items, so that we do not need hard encoding. Therefore, this attribute name is essentially the name of the configuration item.
In this way, we put all the configuration items to be used as attributes in the AppConfigSetting class, and then perform all the operations on the configuration items by operating these attributes.
Ii. How to Use
It is also very simple to use. The Code is as follows:
Var config = ConfigSetting. getCurrentConfiguration (); AppConfigSetting setting = new AppConfigSetting (config); // MessageBox if not set. show ($ "LogFileName: {setting. logFileName} "); // After setting, read setting. logFileName = "log.txt"; MessageBox. show ($ "LogFileName: {setting. logFileName }");
Iii. Supplement
To meet the need to access/store the specified configuration item without adding the configuration item attribute to AppConfigSetting, we can add the following three methods to the base class ConfigSetting:
/// <Summary> /// return the value of the specified configuration item /// </summary> /// <param name = "settingKey"> </param> /// <returns> </returns> public string GetSettingValueByKey (string settingKey) {return GetSettingValue (settingKey );} /// <summary> /// return the value of the specified configuration item /// </summary> /// <param name = "settingKey"> </param> /// <returns> </returns> public T GetSettingValueByKey <T> (string settingKey) {return GetSettingValue <T> (settingKey );} /// <summary> /// set the value for the specified configuration item /// </summary> /// <param name = "value"> </param> /// <param name = "settingKey"> </param> public void SetSettingValueByKey (string settingKey, object value) {SetSettingValue (value, settingKey );}
Using these methods, you can freely access/store configuration items. Unlike adding properties above, you need to pass the configuration item key as the parameter.
Usage:
// MessageBox if not set. show ($ "LogLevel: {setting. getSettingValueByKey ("LogLevel")} "); // After setting, read setting. setSettingValueByKey ("LogLevel", 5); MessageBox. show ($ "LogLevel: {setting. getSettingValueByKey ("LogLevel ")}");
Summary
This article mainly introduces a more convenient way to access the application configuration, the main idea is to use the GetSettingValue/SetSettingValue methods in the base class to obtain the name of the attribute in the derived class by using the CallerMemberName feature and operate the corresponding configuration item. Of course, this not only provides a method, but also provides a way of thinking. Based on this, you can also adjust and expand to meet your actual needs.
Source code download