53 lines
2.2 KiB
C#
53 lines
2.2 KiB
C#
namespace Kit.Helpers.Repository
|
|
{
|
|
using System.Collections.Generic;
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
public interface IDictionaryCacheProvider
|
|
{
|
|
void SetByKey<TKey, TValue>(string cacheKey, TKey key, TValue value);
|
|
TValue GetByKey<TKey, TValue>(string cacheKey, TKey key);
|
|
TValue GetByKey<TKey, TValue>(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<TKey, TValue> GetOrCreateDictionary<TKey, TValue>(string cacheKey)
|
|
{
|
|
HttpContext httpContext = HttpContextCore.Current;
|
|
if (httpContext == null) return null;
|
|
var cacheDictionary = httpContext.Items.ContainsKey(cacheKey) ? (Dictionary<TKey, TValue>)httpContext.Items[cacheKey] : null;
|
|
|
|
if (cacheDictionary == null)
|
|
{
|
|
cacheDictionary = new Dictionary<TKey, TValue>();
|
|
httpContext.Items[cacheKey] = cacheDictionary;
|
|
}
|
|
return cacheDictionary;
|
|
}
|
|
|
|
public void SetByKey<TKey, TValue>(string cacheKey, TKey key, TValue value) => GetOrCreateDictionary<TKey, TValue>(cacheKey).SetByKey(key, value);
|
|
public TValue GetByKey<TKey, TValue>(string cacheKey, TKey key) => GetOrCreateDictionary<TKey, TValue>(cacheKey).GetByKey(key);
|
|
public TValue GetByKey<TKey, TValue>(string cacheKey, TKey key, TValue defaultValue) => GetOrCreateDictionary<TKey, TValue>(cacheKey).GetByKey(key, defaultValue);
|
|
|
|
}
|
|
}
|