Skip to content

REQUEST - Caching

Our caching provider is built on top of Microsoft.Extensions.Caching.Memory Caching is insanely easy with request handlers in Shiny Mediator.

  1. Install Shiny.Mediator.Caching to your project.

  2. Create your request handler - you can mark Cache here with the attribute or you can use Configuration.

    [Cache]
    public class MyHandler : IRequestHandler<MyRequest, MyResult>
    {
    public async Task<MyResult> Handle(MyRequest request, CancellationToken ct)
    {
    return new MyResult();
    }
    }
  3. In your host startup, with the AddShinyMediator call, add the following:

    services.AddShinyMediator(x => x..AddMemoryCaching(y =>
    {
    y.ExpirationScanFrequency = TimeSpan.FromSeconds(5);
    }));

There are many additional properties you can use to interact with the cache setup

public class CacheAttribute : Attribute
{
public CacheItemPriority Priority { get; set; } = CacheItemPriority.Normal;
public int AbsoluteExpirationSeconds { get; set; }
public int SlidingExpirationSeconds { get; set; }
}

Deeper Cache Control

You can add the ICacheControl to your contract to control cache directly at the point of call.

ForceRefresh allows an easy way to bypass cache and SetEntry allows you to set cache entry properties.

public class MyContract : IRequest<SomeResponse>, ICacheControl
{
public bool ForceRefresh { get; set; }
public Action<ICacheEntry>? SetEntry { get; set; } // optional: allows you to set cache entry properties
}

Configuration

We recommend configuring cache through Microsoft.Extensions.Configuration. Read Configuration for more information.

{
"Mediator": {
"Cache": {
"My.Namespace.MyHandler": {
"Priority": "High",
"AbsoluteExpirationSeconds": 60,
"SlidingExpirationSeconds": 30
}
}
}
}