ICacheService
Distributed cache abstraction.
Methods
| Method | Return | Description |
|---|---|---|
| GetAsync<T>(string, CancellationToken) | Task<T?> | Get cached value |
| SetAsync<T>(string, T, TimeSpan?, CancellationToken) | Task | Set with expiration |
| SetWithSlidingExpirationAsync<T>(string, T, TimeSpan, CancellationToken) | Task | Sliding expiration |
| RemoveAsync(string, CancellationToken) | Task | Remove by key |
| RemoveByPatternAsync(string, CancellationToken) | Task | Remove 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<Product?> 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);
}
}