Add Cache System to Web Project
ikesnowy opened this issue · 0 comments
ikesnowy commented
Using midiatR, we could easily archive something like this to simplify query cache.
public class CacheBehavior<TQuery, TResponse> : IPipelineBehavior<TQuery, TResponse>
where TQuery : ICachableQuery
where TResponse : ICachableQueryResponse
{
public async Task<TResponse> Handle(TQuery request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
if (request.AllowCache == false)
{
return await next();
}
var cacheResult = await _cacheService.Get<TResponse>(request.CacheKey);
if (cacheResult is not null)
{
return cacheResult;
}
var freshResult = await next();
await _cacheService.Add<TResponse>(request.CacheKey, request.CacheTime);
return freshResult;
}
}