程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> Introduction to configuration wrapper

Introduction to configuration wrapper

編輯:關於C++

/* 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();

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

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

//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.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved