-
-
Save thangchung/129dfd3e89c0e64ba593a1be91ba9e1b to your computer and use it in GitHub Desktop.
Adding cache to MediatR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CachePipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> | |
{ | |
private readonly IDistributedCache cache; | |
private readonly ILogger<SGUKAspNetCore> logger; | |
public CachePipelineBehavior( | |
IDistributedCache cache, | |
ILogger<SGUKAspNetCore> logger) | |
{ | |
Ensure.Argument.NotNull(cache, nameof(cache)); | |
Ensure.Argument.NotNull(logger, nameof(logger)); | |
this.cache = cache; | |
this.logger = logger; | |
} | |
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) | |
{ | |
if (request is ICacheable cacheableRequest) | |
{ | |
var key = cacheableRequest.GetCacheKey(); | |
return await cache.GetOrSet( | |
key, | |
miss: () => { Log.CacheMiss(logger, key); return next(); }, | |
hit: (data) => Log.CacheHit(logger, key), | |
cacheableRequest.GetExpirationTime(), | |
cancellationToken); | |
} | |
var response = await next(); | |
if (request is ICacheableInvalidation cacheInvalidationRequest) | |
{ | |
foreach (var key in cacheInvalidationRequest.GetCacheKeys()) | |
{ | |
await cache.Remove(key, cancellationToken); | |
} | |
} | |
return response; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICacheable | |
{ | |
public string GetCacheKey(); | |
public TimeSpan? GetExpirationTime() => null; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ICacheableInvalidation | |
{ | |
public IEnumerable<string> GetCacheKeys(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment