Skip to content

ICacheService

Distributed cache abstraction.

Methods

MethodReturnDescription
GetAsync<T>(string, CancellationToken)Task<T?>Get cached value
SetAsync<T>(string, T, TimeSpan?, CancellationToken)TaskSet with expiration
SetWithSlidingExpirationAsync<T>(string, T, TimeSpan, CancellationToken)TaskSliding expiration
RemoveAsync(string, CancellationToken)TaskRemove by key
RemoveByPatternAsync(string, CancellationToken)TaskRemove by pattern
ExistsAsync(string, CancellationToken)Task<bool>Check if exists
GetOrCreateAsync<T>(string, Func<Task<T?>>, TimeSpan?, CancellationToken)Task<T?>Get or create

Usage

csharp
public class ProductService
{
    private readonly ICacheService _cache;
    private readonly IProductRepository _repo;

    public async Task&lt;Product?&gt; GetProductAsync(Guid id, CancellationToken ct)
    {
        var cacheKey = "product:"+id;
        return await _cache.GetOrCreateAsync(
            cacheKey,
            () => _repo.GetByIdAsync(id, ct),
            TimeSpan.FromMinutes(5),
            ct);
    }

    public async Task InvalidateProductAsync(Guid id, CancellationToken ct)
    {
        await _cache.RemoveAsync("product:"+id, ct);
    }
}

Released under the MIT License.