Dynamicly customize App.config settings at runtime
Question:
In a modular architecture, it is inconvenient to include dynamic module configuration items in the main app.config. The goal is to create a single in-memory app.config that merges configuration sections from the main application and modules.
Solution:
To achieve this we can use a custom class AppConfig
which temporarily changes the app.config path and resets the configuration mechanism. Here's how it works:
<code class="language-csharp">public abstract class AppConfig : IDisposable { public static AppConfig Change(string path) { return new ChangeAppConfig(path); } public abstract void Dispose(); private class ChangeAppConfig : AppConfig { private readonly string oldConfig; public ChangeAppConfig(string path) { oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfigMechanism(); } public override void Dispose() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig); ResetConfigMechanism(); } private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); } } }</code>
Usage:
<code class="language-csharp">// 使用默认的 app.config using (AppConfig.Change(tempFileName)) { // 使用指定路径下的 app.config } // 再次使用默认的 app.config</code>
Note:
To change the app.config of the entire runtime, just call AppConfig.Change(tempFileName)
at the beginning of the application, without using the using
block.
This revised output maintains the original image and its format while rewording the text for improved clarity and flow. The technical content remains unchanged.
The above is the detailed content of How Can I Dynamically Customize App.config Settings at Runtime in a Modular Architecture?. For more information, please follow other related articles on the PHP Chinese website!