/* by Dylan SUN */
In your applications, you is certainly using the configuration sections like AppSettings for custom configurations, Conne Ctionstrings for database binding and other sections like WCF bindings, etc.
Your application more flexible for unit testing, you could use a configuration wrapper to control the access to th E configuration file.
You can create a interface to expose some methods to access different configurations.
This is a methods to retrieve the AppSettings and connectionStrings by the configuration key.
publicinterface IConfigurationReader { string GetAppSettings(string key); string GetConnectionString(string key); }
Here is their implementation.
publicclass ConfigurationReader : IConfigurationReader { publicstringGetAppSettings(string key) { return ConfigurationManager.AppSettings[key]; } publicstringGetConnectionString(string key) { return ConfigurationManager.ConnectionStrings[key].ConnectionString; } }
You can register the interface and its implementation with dependency injection pattern using UnityContainer.
containernew UnityContainer();//register interface and its implementationcontainer.RegisterType<IConfigurationReader, ConfigurationReader>();
Resolve the interface and use the class to access the configuration value.
//resolve the interfacevar configurationReader = container.Resolve<IConfigurationReader>();//access GetAppSettings method to get the valuevarvalue = configurationReader.GetAppSettings("hello");Console.WriteLine(value);
You can even centralize the configuration keys with a static class to facilitate the configuration key management.
I Hope you find this article useful! Thanks.
Introduction to Configuration Wrapper