Introduction to configuration wrapper

/* By Dylan SUN */

In your applications, you are certainly using the configuration sections like appSettings for custom configurations, connectionStrings for database binding and other sections like WCF bindings, etc.

To make your application more flexible for unit testing, you could use a configuration wrapper to control the access to the configuration file.

You can create an interface to expose some methods to access different configurations.

This is two methods to retrieve the appSettings and connectionStrings by the configuration key.

public interface IConfigurationReader{string GetAppSettings(string key);string GetConnectionString(string key);}

Here are their implementation.

public class ConfigurationReader : IConfigurationReader{(string key){return ConfigurationManager.AppSettings[key];}(string key){return ConfigurationManager.ConnectionStrings[key].ConnectionString;}}

You can register the interface and its implementation with dependency injection pattern using UnityContainer.

IUnityContainer container = new 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>();= configurationReader.GetAppSettings(“hello”);Console.WriteLine(value);

You can even centralize the configuration keys in a static class to facilitate the configuration key management.

I hope you find this article useful! Thanks.

,经受雨,面对另一个轮回。

Introduction to configuration wrapper

相关文章:

你感兴趣的文章:

标签云: