Dynamically Adjusting App.config at Runtime: A Clean Approach
In application development, dynamically loaded modules often necessitate adjustments to the app.config
file. However, directly altering the main app.config
is generally avoided due to potential conflicts and instability.
The Challenge: ConfigurationManager and Caching
The ConfigurationManager
class and the System.Configuration
namespace employ caching. This means that changes made after the initial configuration load might not take effect until the application restarts.
The Solution: The AppConfig Class
The following AppConfig
class provides a solution to this problem. It allows modifying the app.config
for runtime modules without affecting the original file.
<code class="language-csharp">public abstract class AppConfig : IDisposable { public static AppConfig Change(string path) { return new ChangeAppConfig(path); } protected abstract void Dispose(); private class ChangeAppConfig : AppConfig { private readonly string originalConfigPath = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); private bool disposedValue; public ChangeAppConfig(string path) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfiguration(); } public override void Dispose() { if (!disposedValue) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", originalConfigPath); ResetConfiguration(); disposedValue = true; } GC.SuppressFinalize(this); } private static void ResetConfiguration() { // Resetting internal ConfigurationManager state to reload config 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>
How to Use It
<code class="language-csharp">// Temporary config modification using (AppConfig.Change(temporaryConfigPath)) { // Access and use the modified configuration } // Permanent config modification (replace default) AppConfig.Change(newConfigPath);</code>
Advantages
This method offers a clean and efficient way to manage configuration for dynamically loaded modules. It avoids directly altering the default app.config
, ensuring stability and preventing conflicts. Its straightforward implementation makes it adaptable to various scenarios requiring runtime configuration changes.
The above is the detailed content of How Can I Dynamically Modify an App.config File at Runtime Without Affecting the Default Settings?. For more information, please follow other related articles on the PHP Chinese website!