fix: resolve thread safety issues in ConfigService cache (#98)

Co-authored-by: admin <admin@ardentleatherworks.com>
This commit is contained in:
Cody Kickertz 2025-12-21 11:58:46 -06:00 committed by GitHub
parent d8c69e87e2
commit 1a5ca83f4f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -25,14 +25,14 @@ public class ConfigService : IConfigService
private readonly IConfigRepository _repository;
private readonly IEventAggregator _eventAggregator;
private readonly Logger _logger;
private static Dictionary<string, string> _cache;
private static readonly object _cacheLock = new object();
private static Dictionary<string, string> _cache = new Dictionary<string, string>();
public ConfigService(IConfigRepository repository, IEventAggregator eventAggregator, Logger logger)
{
_repository = repository;
_eventAggregator = eventAggregator;
_logger = logger;
_cache = new Dictionary<string, string>();
}
private Dictionary<string, object> AllWithDefaults()
@ -491,9 +491,12 @@ public string GetValue(string key, object defaultValue, bool persist = false)
EnsureCache();
if (_cache.TryGetValue(key, out var dbValue) && dbValue != null && !string.IsNullOrEmpty(dbValue))
lock (_cacheLock)
{
return dbValue;
if (_cache.TryGetValue(key, out var dbValue) && dbValue != null && !string.IsNullOrEmpty(dbValue))
{
return dbValue;
}
}
_logger.Trace("Using default config value for '{0}' defaultValue:'{1}'", key, defaultValue);
@ -533,21 +536,24 @@ private void SetValue(string key, string value)
private void EnsureCache()
{
lock (_cache)
lock (_cacheLock)
{
if (!_cache.Any())
{
var all = _repository.All();
_cache = all.ToDictionary(c => c.Key.ToLower(), c => c.Value);
foreach (var item in all)
{
_cache[item.Key.ToLower()] = item.Value;
}
}
}
}
private static void ClearCache()
{
lock (_cache)
lock (_cacheLock)
{
_cache = new Dictionary<string, string>();
_cache.Clear();
}
}
}