Methods to implement caching in ASP.NET Core minimal APIs

In-memory caching in minimal APIs

ASP.NET Core gives help for 2 abstractions for working with caching, IMemoryCache and IDistributedCache. Whereas the previous is used to implement in-memory caching, the latter is used to implement distributed caching.

The next use of IMemoryCache reveals how one can retrieve knowledge from the cache if the requested knowledge is offered. If the info requested just isn’t current within the in-memory cache, the applying will retrieve the info from the info retailer (utilizing a repository), retailer the info within the in-memory cache, and return it.


app.MapGet("authors/getall", (IMemoryCache cache, 
IAuthorRepository authorRepository) =>
    {
        if (!cache.TryGetValue("get-authors", 
            out Record authors))
        {
            authors = authorRepository.GetAll();
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(5))
                .SetSlidingExpiration(TimeSpan.FromMinutes(1));
            cache.Set("get-authors", authors, cacheEntryOptions);
        }
        return Outcomes.Okay(authors);
    });

As you possibly can see within the previous code snippet, the cached content material will reside within the reminiscence for a most of 30 seconds.

Distributed caching in minimal APIs

Distributed caching enhances the efficiency and scalability of functions by distributing the load throughout a number of nodes or servers. The servers could be positioned both in the identical community or in several networks which can be unfold throughout geographical distances.

The next code demonstrates methods to implement distributed caching in a minimal API endpoint in ASP.NET Core. On this instance, the endpoint returns all writer information from the distributed cache if the info is offered within the cache. If the requested knowledge just isn’t obtainable within the distributed cache, the endpoint provides the info to the cache after which returns the info. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles