How you can implement caching in ASP.NET Core minimal APIs

Learn extra at:

In-memory caching in minimal APIs

ASP.NET Core gives assist 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 obtainable. If the info requested isn’t current within the in-memory cache, the appliance 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 Checklist 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 purposes by distributing the load throughout a number of nodes or servers. The servers could be situated both in the identical community or in numerous networks which can be unfold throughout geographical distances.

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

Turn leads into sales with free email marketing tools (en)

Leave a reply

Please enter your comment!
Please enter your name here