Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an ASP.NET Core 5.0 MVC application, install the LazyCache.AspNetCore package, register LazyCache in Startup.ConfigureServices, then inject IAppCache and use GetOrAdd around work that is safe to reuse. This guide covers that ASP.NET Core setup; ASP.NET Core 5.0 is not the same framework as legacy ASP.NET MVC 5 on .NET Framework.

First, confirm which “MVC 5” you mean

“ASP.NET Core MVC 5” can refer to two different targets. ASP.NET Core 5.0 is based on .NET 5 and uses the ASP.NET Core hosting model, including a Startup class in the setup shown here. Legacy ASP.NET MVC 5 is a separate framework built on .NET Framework, so these Startup-based instructions do not apply to it. Microsoft explains the naming distinction in its ASP.NET Core migration documentation.

The rest of this article assumes an existing ASP.NET Core 5.0 MVC app that has Startup.ConfigureServices.

Install and register LazyCache

Use the ASP.NET Core integration package so LazyCache can be registered with the built-in dependency injection container. The versioned NuGet listing identifies LazyCache.AspNetCore 2.4.0 as targeting .NET Standard 2.0, which is compatible with .NET 5. Check the LazyCache.AspNetCore NuGet page and your project’s dependency constraints before choosing a version; the related LazyCache 2.4.0 package also targets .NET Standard 2.0.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Add LazyCache.AspNetCore to the application, for example with the NuGet Package Manager or the dotnet add package LazyCache.AspNetCore command.

  2. In Startup.cs, keep the application’s existing MVC registration and add services.AddLazyCache() in ConfigureServices:

    using LazyCache;
    using Microsoft.Extensions.DependencyInjection;
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews(); // Or retain the app's existing MVC registration.
        services.AddLazyCache();
    }

The project’s quickstart and documentation show this dependency-injection approach. If an application is not using DI, the quickstart also demonstrates manual construction with new CachingService(); in a standard ASP.NET Core application, registering the service and injecting it is the more natural fit.

Inject IAppCache and cache an operation

Inject IAppCache into the controller or service that owns the work to be cached. Pass GetOrAdd a stable key and a factory function. When a usable entry exists, the cached value can be returned instead of running the factory again; when it does not, the factory supplies the value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using System.Linq;
using LazyCache;
using Microsoft.AspNetCore.Mvc;

public class CatalogController : Controller
{
    private readonly IAppCache cache;
    private readonly ProductDbContext db;

    public CatalogController(IAppCache cache, ProductDbContext db)
    {
        this.cache = cache;
        this.db = db;
    }

    public IActionResult Index()
    {
        var products = cache.GetOrAdd(
            "CatalogController.Index.Products",
            () => db.Products.ToList());

        return View(products);
    }
}

The example caches the result of a database query, not the controller action or rendered view. Choose a key that identifies both the data and every input that can change the result. For example, if the result depends on a tenant, locale, filter, or user-specific permission, include the relevant value in the key; otherwise, unrelated requests can collide and receive the wrong cached value. LazyCache’s documented API and usage examples are in the project documentation.

For asynchronous data access, use LazyCache’s asynchronous API, including GetOrAddAsync, as documented by the project. Keep the factory’s operation aligned with the method’s async behavior rather than blocking on asynchronous database work.

Set freshness and plan for cache misses

LazyCache is an in-memory cache. Decide how long a result may safely remain stale based on the data’s update frequency and the cost of recalculating or reloading it. Configure expiration for entries as appropriate to the API and version in use, and ensure the underlying data source remains the normal recovery path when an entry expires or is absent. A cache is an optimization, not durable storage: Microsoft advises against depending on cached data being available and recommends controls such as expiration and size limits to constrain cache growth. See Microsoft’s in-memory caching guidance.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the cache type for your deployment

An in-memory cache is local to an individual web server. In a multi-server deployment, requests may reach different instances and therefore see different local entries. Microsoft notes that non-sticky sessions across a server farm can create cache consistency issues. If requests need shared cache state, or consistency across instances matters, assess a distributed cache rather than assuming a local LazyCache entry is shared. Compare the options against your deployment and freshness requirements:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Option Cache behavior When it fits
LazyCache / in-process memory Entries reside in an individual application server’s memory. A suitable choice when local caching is sufficient and the app can tolerate per-instance entries and cache misses.
Distributed cache Cache state can be shared outside an individual web server. Consider it when requests can land on different servers and shared state or consistency is required.
HybridCache Microsoft describes it as a unified in-process and distributed caching API with stampede protection; it was introduced in .NET 9. Assess for new or modernized applications targeting a supported runtime. Details are in Microsoft’s HybridCache overview.

Microsoft’s broader caching guidance covers IMemoryCache and IDistributedCache. LazyCache offers a higher-level IAppCache/GetOrAdd workflow; the built-in APIs may be a better fit when you want to work directly with platform caching abstractions.

Account for .NET 5 support status

.NET 5.0 support ended on May 11, 2022, and ASP.NET Core follows the lifecycle of its parent .NET release. Microsoft lists this date on its .NET and .NET Core support policy. Treat ASP.NET Core 5.0 as a legacy maintenance target, not the default for new work; plan runtime modernization alongside decisions about keeping LazyCache, using IMemoryCache or IDistributedCache, or evaluating HybridCache. The LazyCache project’s README also recommends considering HybridCache for new projects and migration of older ones.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.