namespace Kit.Helpers.Repository { using System.Collections.Generic; using Microsoft.AspNetCore.Http; public interface IDictionaryCacheProvider { void SetByKey(string cacheKey, TKey key, TValue value); TValue GetByKey(string cacheKey, TKey key); TValue GetByKey(string cacheKey, TKey key, TValue defaultValue); } public static class HttpDictionaryCacheHelper { public static bool IsConfigured => _isConfigured; public static IDictionaryCacheProvider Instance => _instance; private static bool _isConfigured = false; private static IDictionaryCacheProvider _instance; public static void Configure(IDictionaryCacheProvider instance) { _instance = instance; _isConfigured = _instance != null; } } public class HttpDictionaryCacheProvider : IDictionaryCacheProvider { public static HttpDictionaryCacheProvider Instance { get; } = new HttpDictionaryCacheProvider(); public static void InitHelpers() => HttpDictionaryCacheHelper.Configure(Instance); private HttpDictionaryCacheProvider() { } private IDictionary GetOrCreateDictionary(string cacheKey) { HttpContext httpContext = HttpContextCore.Current; if (httpContext == null) return null; var cacheDictionary = httpContext.Items.ContainsKey(cacheKey) ? (Dictionary)httpContext.Items[cacheKey] : null; if (cacheDictionary == null) { cacheDictionary = new Dictionary(); httpContext.Items[cacheKey] = cacheDictionary; } return cacheDictionary; } public void SetByKey(string cacheKey, TKey key, TValue value) => GetOrCreateDictionary(cacheKey).SetByKey(key, value); public TValue GetByKey(string cacheKey, TKey key) => GetOrCreateDictionary(cacheKey).GetByKey(key); public TValue GetByKey(string cacheKey, TKey key, TValue defaultValue) => GetOrCreateDictionary(cacheKey).GetByKey(key, defaultValue); } }