AppSettings.cs
public static class AppSettings { public static T GetSettingByKey<T>(string key, T defaultValue = default(T)) { key = key.Trim().ToLowerInvariant(); var settings = GetAllSettings(); if (settings.ContainsKey(key)) return CommonHelper.To<T>(settings[key].Value); return defaultValue; } public static TSettings GetSetting<TSettings>() { var Settings = Activator.CreateInstance<TSettings>(); // get properties we can write to var properties = from prop in typeof(TSettings).GetProperties() where prop.CanWrite && prop.CanRead let setting = AppSettings.GetSettingByKey<string>(typeof(TSettings).Name + "." + prop.Name) where setting != null where CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).CanConvertFrom(typeof(string)) where CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).IsValid(setting) let value = CommonHelper.GetNopCustomTypeConverter(prop.PropertyType).ConvertFromInvariantString(setting) select new { prop, value }; // assign properties properties.ToList().ForEach(p => p.prop.SetValue(Settings, p.value, null)); return Settings; } public static IDictionary<string, KeyValuePair<int, string>> GetAllSettings() { var settings = new Dictionary<string, KeyValuePair<int, string>>(); var appSettings = ConfigurationManager.AppSettings; foreach (var setting in appSettings.AllKeys) { settings.Add(setting.ToLowerInvariant(), new KeyValuePair<int, string>(0, appSettings[setting])); } return settings; } }
CommonHelper.cs
/// <summary> /// Represents a common helper /// </summary> public partial class CommonHelper { /// <summary> /// Converts a value to a destination type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="destinationType">The type to convert the value to.</param> /// <returns>The converted value.</returns> public static object To(object value, Type destinationType) { return To(value, destinationType, CultureInfo.InvariantCulture); } /// <summary> /// Converts a value to a destination type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="destinationType">The type to convert the value to.</param> /// <param name="culture">Culture</param> /// <returns>The converted value.</returns> public static object To(object value, Type destinationType, CultureInfo culture) { if (value != null) { var sourceType = value.GetType(); TypeConverter destinationConverter = GetNopCustomTypeConverter(destinationType); TypeConverter sourceConverter = GetNopCustomTypeConverter(sourceType); if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType())) return destinationConverter.ConvertFrom(null, culture, value); if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType)) return sourceConverter.ConvertTo(null, culture, value, destinationType); if (destinationType.IsEnum && value is int) return Enum.ToObject(destinationType, (int)value); if (!destinationType.IsAssignableFrom(value.GetType())) return Convert.ChangeType(value, destinationType, culture); } return value; } /// <summary> /// Converts a value to a destination type. /// </summary> /// <param name="value">The value to convert.</param> /// <typeparam name="T">The type to convert the value to.</typeparam> /// <returns>The converted value.</returns> public static T To<T>(object value) { //return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture); return (T)To(value, typeof(T)); } public static TypeConverter GetNopCustomTypeConverter(Type type) { /*if (type == typeof(List<int>)) return new GenericListTypeConverter<int>();*/ return TypeDescriptor.GetConverter(type); } }
App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Setting1" value="SomeValue"/> <add key="Setting2" value="25"/> <add key="Setting3" value="12/25/2010"/> <add key="TestSettings.ServerName" value="Ruby"/> <add key="TestSettings.Ip" value="192.168.0.1"/> <add key="TestSettings.PortNumber" value="21"/> <add key="TestSettings.Username" value="admin"/> <add key="TestSettings.Password" value="password"/> </appSettings> </configuration>
UnitTest1.cs
[TestMethod] public void Can_get_all_settings() { var settings = AppSettings.GetAllSettings(); Assert.IsNotNull(settings); Assert.IsTrue(settings.Count > 0); } [TestMethod] public void Can_get_setting_by_key() { var setting = AppSettings.GetSettingByKey<string>("Setting1"); Assert.AreEqual(setting, "SomeValue"); } [TestMethod] public void Can_get_typed_setting_value_by_key() { var setting = AppSettings.GetSettingByKey<DateTime>("Setting3"); Assert.AreEqual(setting, new DateTime(2010, 12, 25)); } [TestMethod] public void Default_value_returned_if_setting_does_not_exist() { var setting = AppSettings.GetSettingByKey<int>("NonExistentKey", 100); Assert.AreEqual(setting, 100); } [TestMethod] public void Can_get_settings() { // requires settings to be set in app.config in format TestSettings.[PropertyName] var settings = AppSettings.GetSetting<TestSettings>(); settings.ServerName.ShouldEqual("Ruby"); settings.Ip.ShouldEqual("192.168.0.1"); settings.PortNumber.ShouldEqual(21); settings.Username.ShouldEqual("admin"); settings.Password.ShouldEqual("password"); }
学习nop中读取配置文件的方式。读取方法改成了静态方法。提取出来单独使用。