I have the below code and now I want to add an UpdateSetting
method.
The best way of doing this that I can see is via TryUpdate
on the ConcurrentDictionary
but that means knowing the previous value so that would require a call to GetSetting
which seems a bit yucky. What are your thoughts? Is there a better way?
NOTE: If the value is not in the cache it should do nothing. On successful updating of cache it should call the settingRepository.Update
Thanks
public class MySettings : IMySettings
{
private readonly ISettingRepository settingRepository;
private readonly ConcurrentDictionary<string, object> cachedValues = new ConcurrentDictionary<string, object>();
public MySettings(ISettingRepository settingRepository)
{
this.settingRepository = settingRepository;
}
public string GetSetting(string key)
{
return this.GetSetting<string>(key);
}
public T GetSetting<T>(string key)
{
object value;
if (!this.cachedValues.TryGetValue(key, out value))
{
value = this.GetValueFromRepository(key, typeof(T));
this.cachedValues.TryAdd(key, value);
}
return (T)value;
}
private object GetValueFromRepository(string key, Type type)
{
var stringValue = this.settingRepository.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);
}
}