码迷,mamicode.com
首页 > 移动开发 > 详细

Introduction to configuration wrapper

时间:2015-02-08 18:10:15      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

/* 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
    {
        public string GetAppSettings(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        public string GetConnectionString(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 implementation
container.RegisterType<IConfigurationReader, ConfigurationReader>();

Resolve the interface and use the class to access the configuration value.

//resolve the interface
var configurationReader = container.Resolve<IConfigurationReader>();

//access GetAppSettings method to get the value
var value = 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

标签:

原文地址:http://blog.csdn.net/garcon1986/article/details/43638875

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!