using System.Collections; using System.Collections.Immutable; namespace Connected.Caching; public abstract class CacheClient : ICacheClient where TEntry : class { protected CacheClient(ICachingService cachingService, string key) { if (cachingService is null) throw new ArgumentException(nameof(cachingService)); CachingService = cachingService; Key = key; } public string Key { get; } protected bool IsDisposed { get; set; } protected async Task Remove(TKey id) { if (id is null) throw new ArgumentNullException(nameof(id)); await CachingService.Remove(Key, id); } protected async Task Remove(Func predicate) { await CachingService.Remove(Key, predicate); } protected async Task Refresh(TKey id) { if (id is null) throw new ArgumentNullException(nameof(id)); await CachingService.Invalidate(Key, id); } protected ICachingService CachingService { get; } public int Count => CachingService.Count(Key); protected virtual ICollection? Keys => CachingService.Keys(Key); protected virtual Task?> All() { return Task.FromResult(CachingService.All(Key)); } protected virtual async Task Get(TKey id, Func> retrieve) { if (id is null) throw new ArgumentNullException(nameof(id)); return await CachingService.Get(Key, id, retrieve); } protected virtual Task Get(TKey id) { if (id is null) throw new ArgumentNullException(nameof(id)); return Task.FromResult(CachingService.Get(Key, id)); } protected virtual Task First() { return Task.FromResult(CachingService.First(Key)); } protected virtual async Task Get(Func predicate) { return await CachingService.Get(Key, predicate, null); } protected virtual Task?> Where(Func predicate) { return Task.FromResult(CachingService.Where(Key, predicate)); } protected virtual void Set(TKey id, TEntry instance) { if (id is null) throw new ArgumentNullException(nameof(id)); CachingService.Set(Key, id, instance); } protected virtual void Set(TKey id, TEntry instance, TimeSpan duration) { if (id is null) throw new ArgumentNullException(nameof(id)); CachingService.Set(Key, id, instance, duration); } private void Dispose(bool disposing) { if (!IsDisposed) { if (disposing) OnDisposing(); IsDisposed = true; } } protected virtual void OnDisposing() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual IEnumerator GetEnumerator() { return CachingService?.GetEnumerator(Key); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }