Last active
December 26, 2015 12:49
-
-
Save khellang/7153964 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class AppSettings : IAppSettings | |
| { | |
| private readonly ConcurrentDictionary<string, object> _cachedValues = new ConcurrentDictionary<string, object>(); | |
| private readonly Func<ISettingsRepository> _repositoryFactory; | |
| public AppSettings(Func<ISettingsRepository> repositoryFactory) | |
| { | |
| _repositoryFactory = repositoryFactory; | |
| } | |
| public string GetSetting(string key) | |
| { | |
| return GetSetting<string>(key); | |
| } | |
| public T GetSetting<T>(string key) | |
| { | |
| object value; | |
| if (!_cachedValues.TryGetValue(key, out value)) | |
| { | |
| value = GetValueFromRepository(key, typeof(T)); | |
| _cachedValues.TryAdd(key, value); | |
| } | |
| return (T) value; | |
| } | |
| private object GetValueFromRepository(string key, Type type) | |
| { | |
| var stringValue = _repositoryFactory.Invoke().GetSetting(key); | |
| if (stringValue == null) | |
| { | |
| throw new MissingSettingException(string.Format("A setting with the key '{0}' does not exist.", key)); | |
| } | |
| if (type == typeof(string)) | |
| { | |
| return stringValue; | |
| } | |
| return ConvertValue(stringValue, type); | |
| } | |
| private static object ConvertValue(string stringValue, Type type) | |
| { | |
| return TypeDescriptor.GetConverter(type).ConvertFromString(stringValue); | |
| } | |
| } | |
| public class MissingSettingException : Exception | |
| { | |
| public MissingSettingException(string message) : base(message) { } | |
| } | |
| public interface ISettingsRepository | |
| { | |
| string GetSetting(string key); | |
| } | |
| public interface IAppSettings | |
| { | |
| string GetSetting(string key); | |
| T GetSetting<T>(string key); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment