CacheService.cs 900 B

1234567891011121314151617181920212223242526272829
  1. using DirectService.Tools;
  2. using System;
  3. using System.Data.SqlClient;
  4. namespace LJLib
  5. {
  6. public class CacheService<TKey, TValue> : ICacheService<TKey, TValue>
  7. where TValue : class, new()
  8. {
  9. private readonly LJCache<TKey, TValue> _cache;
  10. private readonly ICacheLoader<TKey, TValue> _loader;
  11. public CacheService(ICacheLoader<TKey, TValue> loader, int cacheMinutes = 120)
  12. {
  13. _loader = loader ?? throw new ArgumentNullException(nameof(loader));
  14. _cache = new LJCache<TKey, TValue> { DefaultAddMinutes = cacheMinutes };
  15. }
  16. public TValue Get(SqlCommand cmd, TKey key)
  17. {
  18. if (!_cache.TryGetValue(key, out TValue value))
  19. {
  20. value = _loader.Load(cmd, key);
  21. _cache.Add(key, value);
  22. }
  23. return ObjectHelper.DeepCopy(value);
  24. }
  25. }
  26. }