Introduction to Configuration Wrapper

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.