using System.Text.Json; using LexWells.Infrastructure.Common.Interfaces; using Microsoft.Extensions.Caching.Distributed; namespace LexWells.Infrastructure.Common.Services; public class RedisCacheService : ICacheService { private readonly IDistributedCache _cache; public RedisCacheService(IDistributedCache cache) { _cache = cache; } public async Task?> GetCollectionAsync(string key) where TConcrete : T { var cachedData = await _cache.GetStringAsync(key); if (string.IsNullOrEmpty(cachedData)) return null; var result = JsonSerializer.Deserialize>(cachedData); return result?.Cast(); } public async Task GetAsync(string key) { var cachedData = await _cache.GetStringAsync(key); // Explicitly return null if Redis has NOTHING if (string.IsNullOrWhiteSpace(cachedData)) { return default; } try { return JsonSerializer.Deserialize(cachedData); } catch { return default; } } public async Task SetAsync(string key, T value, TimeSpan? expiration = null) { var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration ?? TimeSpan.FromHours(1) }; string dataToStore = value is string s ? s : JsonSerializer.Serialize(value); await _cache.SetStringAsync(key, dataToStore, options); } public async Task RemoveAsync(string key) { await _cache.RemoveAsync(key); } }