#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:IDictionaryRepository where TEntity:IPersistentKey { private string _cacheKey; private ICacheProvider _cacheProvider; public DictionaryRepository(ICacheProvider cacheProvider, string cacheKey) { _cacheProvider = cacheProvider; _cacheKey = cacheKey; } // лучше сделать абстрактным protected abstract IEnumerable GetData(); public IDictionary Select() { IDictionary values = null; if(_cacheKey.IsNullOrEmpty()) { throw new ArgumentNullException("Не задан ключ кеширования для репозитория: {0}".ApplyFormat(this.GetType().ToString())); } if (_cacheProvider.Contains(_cacheKey)) { values = (IDictionary)_cacheProvider.GetCacheData(_cacheKey); } else { IEnumerable data = this.GetData(); values = new Dictionary(); // добавить обработку дубликатов 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 values = this.Select(); if (values.ContainsKey(key)) return values[key]; else return default(TEntity); } public void ClearCache() { _cacheProvider.PurgeCacheItems(_cacheKey); } } }