Alamut.MediatR.Caching

MediatR pipeline caching on the top of the dotnet Core Distributed Caching

9
0
C#

MediatR Caching Behavior

Behaviors allow you to build your own pipeline directly inside of MediatR.

A pipeline behavior is an implementation of IPipelineBehavior<TRequest, TResponse>. It represents a similar pattern to filters in ASP.NET MVC/Web API or pipeline behaviors in NServiceBus.

The simplest implementation that does nothing but calls the next possible behavior.

public class MyPipeline<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
    {
        return await next();
    }
}

Caching Behavior is an implemented Behavior that Caches your response based on ICacheable request.

Registering Caching Behavior

You should register caching-behavior to cache your Request.
If you’re using ASP.NET Code DI you can install Alamut.MediatR.Caching.DependencyInjection package and register it by calling services.AddCachingBehavior(); (take a look at Startup.cs for more info).
Alternatively you can install Alamut.MediatR.Caching and register the behavior services.AddScoped(typeof(IPipelineBehavior<,>), typeof(CachingBehavior<,>));

Setting up Caching

Any Request(query) that Implement ICacheable (its a part of Alamut.Abstraction package) are eligibel to be cached.

public class GetFooByIdQuery : IRequest<FooModel>, ICacheable
    {
        public GetFooByIdQuery(int id)
        {
            Id = id;
            Key = $"Foo_{id}";
            Options = new ExpirationOptions(TimeSpan.FromSeconds(60));
        }

        public int Id { get;  }
        public string Key { get; }
        public ExpirationOptions Options { get; }
    }

By implementing ICacheable you should provide a (unique) key for the cache object and ExpirationOptions.

That’s It! It couldn’t be any easier.
It’s highly recommended to study the ASP.NET Web API sample

Acknowledgements

Alamut.MediatR.Caching is built using the following great open source projects and free services: