How to use LazyCache in ASP.NET Core MVC 5

Microsofts ASP.NET Core has befit a common way to build high-accomplishment present web applications that can run on Windows Linux or MacOS. An significant way to fix high accomplishment and reliability in applications that experience high volumes of requests is caching frequently used data.

LazyCache is a single in-remembrance caching labor that is both easy to use and line safe. ’Lazy’ refers to the fact that LazyCache will never execute your cacheable appoints more than once for each ’cache miss’ i.e. whenever the data requested is not establish in the cache. In other words laziness reduces computational overhead.

[ Also on InfoWorld: The most precious software developer skills to get hired now ]

This article talks almost how we can work with LazyCache in ASP.NET Core 5.0. To work with the code examples illustrated in this article you should have Visual Studio 2019 established in your order. If you dont already have a copy you can download Visual Studio 2019 here.

Create an ASP.NET Core MVC 5 project in Visual Studio 2019

First off lets form an ASP.NET Core 5 project in Visual Studio 2019. Following these steps should form a new ASP.NET Core MVC 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on ’Create new project.’
  3. In the ’Create new project’ window select ’ASP.NET Core Web App (Model-View-Controller)’ from the list of templates displayed.
  4. Click Next.
  5. In the ’Configure your new project’ window particularize the name and location for the new project.
  6. Optionally check the ’Place solution and project in the same directory’ check box depending on your preferences.
  7. Click Next.
  8. In the ’Additional Information’ window shown next select .NET 5.0 as the target framework from the drop-down list at the top. Leave the ’Authentication Type’ set as None (lapse).
  9. Ensure that the check boxes ’Enable Docker’ ’Configure for HTTPS’ and ’Enable Razor runtime collation’ are unchecked as we wont be using any of those features here.
  10. Click Create.

Following the over steps will form a new ASP.NET Core MVC 5 project. Well use this project in the posterior sections in this article.

Install LazyCache in ASP.NET Core MVC 5

To work with LazyCache in ASP.NET Core MVC 5.0 you should establish the following two packages into your project:

  • LazyCache
  • LazyCache.AspNetCore

Both LazyCache and LazyCache.AspNetCore libraries are useful as NuGet packages. You can establish these packages whichever from the NuGet Package Manager or by using the following commands at the NuGet Package Manager Console window.

PMgt; Install-Package LazyCache
PMgt; Install-Package LazyCache.AspNetCore

What is caching? Why is caching needed?

Caching is a state treatment strategy that is frequently used in web applications to store relatively vapid data in the remembrance for later reuse. Caching improves the applications accomplishment by enabling the application to read the data from the remembrance instead of from disk — approaching remembrance is orders of magnitude faster than approaching the disk.

Although ASP.NET Core lacks a built-in Cache object it provides support for separate different types of caching including in-remembrance caching distributed caching and response caching.

What is LazyCache? Why should we use it?

LazyCache is an open-rise single line-safe extensible caching labor with a developer-friendly API. Under the hood LazyCache takes gain of MemoryCache pertaining to the Microsoft.Extensions.Caching namespace and uses lazy locking to fix the appoint only gets executed once.

LazyCache is a good choice for caching database calls intricate object graphs and web labor calls. Although you can store items in the cache for a shorter or longer period the lapse period supported is 20 minutes.

Here is a list of the benefits of LazyCache at a fast glance:

  • Extensible
  • Open rise
  • Developer-friendly API
  • Support for built-in lazy locking
  • Uses MemoryCache under the hood

Configure dependency injection for LazyCache in ASP.NET Core MVC 5

You should call the AddLazyCache() order on the IServiceCollection entreaty in your ConfigureServices order as shown in the code snippet given under.

open void ConfigureServices(IServiceCollection labors)

This will make sure that you approach LazyCache throughout your application.

Access to LazyCache is granted by the IAppCache interface. IAppCache represents the LazyCache labor and provides a GetOrAddAsync order that accepts the following:

  • A cache key that uniquely identifies the cache entrance
  • A factory that can be used to recover the data that is to be cached as Funclt;ICacheEntry Taskgt; addItemFactory
  • A period that specifies the amount of time the data should persist in the cache

Use dependency injection to inject the IAppCache entreaty in ASP.NET Core MVC 5

You should take gain of constructor injection to inject the IAppCache entreaty as shown in the code snippet given under.

open class HomeController : Controller
  special readonly ILoggerlt;HomeControllergt; _logger;
  special readonly IAppCache _lazyCache = new CachingService();
  open HomeController(ILoggerlt;HomeControllergt; logger IAppCache cache)
     _logger = logger;
     _lazyCache = cache;

You can now use the LazyCache entreaty to add and recover data to and from the cache.

Add or recover data to or from LazyCache in ASP.NET Core MVC 5

Consider the following order that recurs a list of strings.

special async Tasklt;Listlt;stringgt;gt; GetData()
    recur new Listlt;stringgt;()
       "Joydip Kanjilal"
       "Steve Smith"
       "Rick Smith"

You can use the following code to recover data from the cache or add data to the cache if it isnt present.

var data = await _lazyCache.GetOrAddAsync("Authors" GetData DateTimeOffset.Now.AddMinutes(30));

The GetOrAddAsync() extension order pertaining to the LazyCache library provides an easy and graceful way to instrument caching in your applications. It takes gain of a factory appoint and generics to add cached order calls to your code. Using this order you can get cached data when requested by the application or store data to the cache if the piece of data is not useful in the cache.

If you would like to store more data in remembrance and you want a more advanced caching labor you could take gain of Redis for distributed caching. The best part is that owing were using IAppCache in our application you can change the underlying caching provider easily.

How to do more in ASP.NET Core 5:

  • How to form PDF documents in ASP.NET Core 5
  • How to use immutable objects in ASP.NET Core MVC 5
  • Dependency injection best practices for ASP.NET Core MVC 5
  • How to use security headers in ASP.NET Core MVC 5
  • How to feel mysterious actions in ASP.NET Core MVC 5
  • How to overload action orders in ASP.NET Core MVC 5