using KBR.Shared.Cache; using Microsoft.Extensions.Caching.Distributed; namespace KBR.Cache { internal class AppDistributedCache : IAppDistributedCache { private readonly IDistributedCache _cache; private readonly DistributedCacheEntryOptions _entryOptions; public AppDistributedCache(IDistributedCache cache) { this._cache = cache; this._entryOptions = new DistributedCacheEntryOptions(); } public T Get(string key) where T : class { if (this._cache.Get(key) is var result && result != null) { return result.FromByteArray(); } return default; } public async Task GetAsync(string key, CancellationToken cancellationToken = default) where T : class { var result = await this._cache.GetAsync(key, cancellationToken); if (result != null) { return result.FromByteArray(); } return default; } public void Set(string key, T obj, DistributedCacheEntryOptions? entryOptions = default) { this._cache.Set(key, obj.ToByteArray(), entryOptions ?? this._entryOptions); } public async Task SetAsync(string key, T obj, DistributedCacheEntryOptions? entryOptions = default, CancellationToken cancellationToken = default) { await this._cache.SetAsync(key, obj.ToByteArray(), entryOptions ?? this._entryOptions, cancellationToken); } public void Remove(string key) { this._cache.Remove(key); } public async Task RemoveAsync(string key, CancellationToken cancellationToken = default) { await this._cache.RemoveAsync(key, cancellationToken); } public TItem GetOrCreate(string key, Func factory) where TItem : class { byte[] result = this._cache.Get(key); var resultData = result?.FromByteArray(); if (result == null || resultData == null) { var data = factory(); this._cache.Set(key, data.ToByteArray(), this._entryOptions); return data; } return resultData; } public async Task GetOrCreateAsync(string key, Func> factory, CancellationToken cancellationToken = default) where TItem : class { byte[] result = await this._cache.GetAsync(key, cancellationToken); var resultData = result?.FromByteArray(); if (result == null || resultData == null) { var data = await factory(); if (data != null) { await this._cache.SetAsync(key, data.ToByteArray(), this._entryOptions, cancellationToken); } return data; } return resultData; } } }