MediatR extension for in memory caching
$ dotnet add package Hflex.MediatR.Extensions.InMemoryCachingCaching extension for MediatR
Inspired by https://github.com/Iamcerba/AspNetCore.CacheOutput
var cachingConfigurations = new CachingConfiguration();
//GetTodoItemsQuery will be invalidated, when timer notification will be fired on InvalidateCacheHostedService
cachingConfigurations.AddConfiguration<GetTodoItemsQuery>(duration: TimeSpan.FromMinutes(2), false);
//GetWeatherForecastsQuery will be invalidated, when UpdateWeatherForecastsCommand called
cachingConfigurations.AddConfiguration<GetWeatherForecastsQuery>(TimeSpan.FromMinutes(10), false, null,
typeof(UpdateWeatherForecastsCommand));
builder.Services.AddRedisCache(cachingConfigurations, builder.Configuration.GetConnectionString("RedisConnectionString"));builder.Services.AddInMemoryCache(cachingConfigurations);Everything does configuration, just register
var cachingConfigurations = new CachingConfiguration();
cachingConfigurations.AddConfiguration<GetWeatherForecastsQuery>(duration: TimeSpan.FromMinutes(10),//Cache duration
perUser: false, //Set to true for caching per user (includes userID into cache key)
keyFactory: null, //Create Func<string> for replacing default key, which is serialized json from request object
invalidatesOnRequests: typeof(UpdateWeatherForecastsCommand), typeof(secondcommand), typeof(thirdCommand) ..... //Command types to invalidate query);
like this for GetWeatherForecastsQuery query, which will get cached for 10 minutes. And once any of invalidatesOnRequests called it will get invalidated automatically. Alternative way of force invalidating queries is to use Notifications. Just publish
_mediator.Publish(new InvalidateCacheNotification { RequestTypes = new Type[]{ typeof(queryType1), typeof(queryType2), ...}});
anywhere in the application e.g. in samples I use hostedService with timer to simulate some domain events, which invalidates GetTodoItemsQuery
_mediator.Publish(new InvalidateCacheNotification { RequestTypes = new []{typeof(GetTodoItemsQuery)} });