You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Framework/Connected.Caching/CacheClient.cs

129 lines
2.7 KiB

using System.Collections;
using System.Collections.Immutable;
namespace Connected.Caching;
public abstract class CacheClient<TEntry, TKey> : ICacheClient<TEntry, TKey> 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<TEntry, bool> 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<string>? Keys => CachingService.Keys(Key);
protected virtual Task<ImmutableList<TEntry>?> All()
{
return Task.FromResult(CachingService.All<TEntry>(Key));
}
protected virtual async Task<TEntry?> Get(TKey id, Func<EntryOptions, Task<TEntry>> retrieve)
{
if (id is null)
throw new ArgumentNullException(nameof(id));
return await CachingService.Get(Key, id, retrieve);
}
protected virtual Task<TEntry?> Get(TKey id)
{
if (id is null)
throw new ArgumentNullException(nameof(id));
return Task.FromResult(CachingService.Get<TEntry>(Key, id));
}
protected virtual Task<TEntry?> First()
{
return Task.FromResult(CachingService.First<TEntry>(Key));
}
protected virtual async Task<TEntry?> Get(Func<TEntry, bool> predicate)
{
return await CachingService.Get(Key, predicate, null);
}
protected virtual Task<ImmutableList<TEntry>?> Where(Func<TEntry, bool> 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<TEntry> GetEnumerator()
{
return CachingService?.GetEnumerator<TEntry>(Key);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}