VEU.WathBody/3-app/1-lib/Kit.Helpers/Repository/DictionaryRepository.cs

74 lines
2.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#if NETCOREAPP
using Microsoft.Extensions.Caching.Memory;
#endif
using Kit.Helpers.Cache;
using System;
using System.Collections.Generic;
namespace Kit.Helpers.Repository
{
public abstract class DictionaryRepository<TKey, TEntity>:IDictionaryRepository<TKey, TEntity>
where TEntity:IPersistentKey<TKey>
{
private string _cacheKey;
private ICacheProvider _cacheProvider;
public DictionaryRepository(ICacheProvider cacheProvider, string cacheKey)
{
_cacheProvider = cacheProvider;
_cacheKey = cacheKey;
}
// лучше сделать абстрактным
protected abstract IEnumerable<TEntity> GetData();
public IDictionary<TKey, TEntity> Select()
{
IDictionary<TKey, TEntity> values = null;
if(_cacheKey.IsNullOrEmpty())
{
throw new ArgumentNullException("Не задан ключ кеширования для репозитория: {0}".ApplyFormat(this.GetType().ToString()));
}
if (_cacheProvider.Contains(_cacheKey))
{
values = (IDictionary<TKey, TEntity>)_cacheProvider.GetCacheData(_cacheKey);
}
else
{
IEnumerable<TEntity> data = this.GetData();
values = new Dictionary<TKey, TEntity>();
// добавить обработку дубликатов
foreach (var item in data)
{
TKey key = item.PersistentKey;
if (values.ContainsKey(key))
{
throw new Exception("Элемент с ключом {0} уже добавлен в коллекцию".ApplyFormat(key));
}
values.Add(item.PersistentKey, item);
}
#if NETFRAMEWORK
_cacheProvider.SetCacheData(_cacheKey, values, new CacheSetProperties { DurationSeconds = 3600, EnableCaching = true });
#elif NETCOREAPP
_cacheProvider.SetCacheData(_cacheKey, values, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(3600), Priority = CacheItemPriority.Normal });
#endif
}
return values;
}
public TEntity Get(TKey key)
{
IDictionary<TKey, TEntity> values = this.Select();
if (values.ContainsKey(key))
return values[key];
else
return default(TEntity);
}
public void ClearCache()
{
_cacheProvider.PurgeCacheItems(_cacheKey);
}
}
}