DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Data
  4. Using Memory Cache in ASP.NET Core

Using Memory Cache in ASP.NET Core

In this post we take a look at examples of how to integrate a memory cache into your ASP.NET Core application. Read on for details.

Gunnar Peipman user avatar by
Gunnar Peipman
·
Apr. 19, 17 · Tutorial
Like (4)
Save
Tweet
Share
11.46K Views

Join the DZone community and get the full member experience.

Join For Free

 Configure()  ASP.NET Core has a memory based caching system similar to what we had in the previous ASP.NET versions. This blog post shows how to use memory cache alone and with support for distributed cache in ASP.NET Core web applications.

Using Memory Cache

Using memory cache starts with adding caching support to services when the application starts up.

public void ConfigureServices(IServiceCollection services)
{                        
    services.AddLogging();
    services.AddMemoryCache();       
    services.AddMvc();
}

As caching has nothing to do with the request pipeline we don’t have to update the Configure()  method of start-up class.

In MVC components, we can use a constructor injection to get the cache's provider instance.

private readonly IMemoryCache _cache;

public HomeController(IMemoryCache cache)
{
    _cache = cache;
}

And here is how to use memory cache in a controller:

public class HomeController : Controller
{
    private readonly IMemoryCache _cache;public HomeController(IMemoryCache cache)
    {
        _cache = cache;
    }
    public IActionResult Index()
    {
        _cache.Set("TestKey", "MyValue");           
        var value = _cache.Get<string>("TestKey");

        return View();
    }
}

But there is a possibility that using only memory cache is not ideal for our situation. 

Distributed Memory Cache

To keep in line with other distributed memory cache providers that follow the IDistributedCache interface, there is also an implementation of memory cache that follows the same interface. The MemoryDistributedCache class is wrapped around the IMemoryCache and we can use it in the same way we would use any other distributed cache. One example of a distributed cache is a SQL Server based cache.

To use distributed memory cache, we have to add it to the application services in our Startup class.

public void ConfigureServices(IServiceCollection services)
{                        
    services.AddLogging();
    services.AddDistributedMemoryCache();       
    services.AddMvc();
}

To inject it into the MVC components, we use a constructor injection with the IDistributedCache interface. In controllers and view components, we will use it as any other distributed cache service.

public class HomeController : Controller
{
    private readonly IDistributedCache _cache;public HomeController(IDistributedCache cache)
    {
        _cache = cache;
    }
    public IActionResult Index()
    {
        _cache.SetString("TestKey", "MyValue");           
        var value = _cache.GetString("TestKey");

        return View();
    }
}

Memory Cache or Distributed Memory Cache?

Using memory cache is the option for systems running on the single box. Also in development environments, we could prefer memory based cache to keep external services away when building the system. I think that going with IDistributedCache is a better idea as there is no need to change controllers and other parts of the application when the distributed cache provider is changed. In cloud and multi-box environments, some implementation of distributed cache is a must, as local caches on a web server are not synchronized.

Wrapping Up

Simple memory-based cache is still available on ASP.NET Core and there are two ways to use it. We can use with IMemoeyCache interface and have only memory based cache supported, or we can go with IDistributedCache interface and have many other cache providers supported. For cloud and clusters, IDistributedCache is preferred, as local caches of web servers are not synchronized.

Cache (computing) ASP.NET Memory (storage engine) ASP.NET Core

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Master Spring Boot 3 With GraalVM Native Image
  • Java Concurrency: LockSupport
  • 10 Most Popular Frameworks for Building RESTful APIs
  • 10 Things to Know When Using SHACL With GraphDB

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: