Skip to content

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

License

Notifications You must be signed in to change notification settings

haamond/Alamut.MediatR.Caching

Repository files navigation

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:

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages