Using Cache in ASP.NET Core 1.0 RC1


When I created my blog in ASP.NET Core, I forgot about one feature that I used to help out some other Pluralsight authors by creating a quick top 100 list of courses. Because Pluralsight doesn’t really expose that data as an API, I didn’t want to hammer their service, so I had been using a memory cache to do it.

But when I moved the code over, I realized that the old, reliable Cache object was missing. Luckily I found it and like much of ASP.NET Core, adding it was simple and consistent. Let me show you.

First thing was to see how caching was being handled. Instead of having different caches, ASP.NET Core has an abstraction around caching and then you can support different types of caches. For me, it was a simple memory cache I wanted so I needed two Nuget packages:

// project.json
{
  ...

  "dependencies": {
    ...
    "Microsoft.Extensions.Caching.Abstractions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final",
    ...

Once I had the packages installed, I had to add caching to the service container:

public void ConfigureServices(IServiceCollection svcs)
{
  ...

  // Add Caching Support
  svcs.AddCaching();

  // Add MVC to the container
  svcs.AddMvc()
    .AddJsonOptions(opts =>
    {
      opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
}

Once caching is available, then in the controller, I can inject an IMemoryCache object:

[Route("")]
public class RootController : Controller
{
  private IMemoryCache _memoryCache;

  public RootController(IMemoryCache memoryCache)
  {
    _memoryCache = memoryCache;
  }

Finally, I’ve done the wire-up so I can use it in my action:

[HttpGet("fromcache")]
public IActionResult CachedString()
{
  var CACHEKEY = "__STRING_TO_CACHE";
  string cached;
  
  if (!_memoryCache.TryGetValue(CACHEKEY, out cached))
  { 
    // Get the string to be cached
    // TODO

    // Decide how to cache it
    var opts = new MemoryCacheEntryOptions() 
    { 
      SlidingExpiration = TimeSpan.FromHours(2) 
    };

    // Store it in cache
    _memoryCache.Set(CACHEKEY, cached, opts);
  }

  return View(cached);
}

I used TryGetValue to see if the value was already cached, and then if not, just added it to the cache. The options object allows you to set caching options like priority, sliding or absolute expiration.

Hope this helps you if you need caching!


Ready to Learn Vue with ASP.NET Core?

Shawn's 4-hour course will get you up to speed in no time. Vue.js is a great middle-ground between React and Angular for people who don't like the complexity of Angular, and the overly componentized React. Learn today at Wilder Minds Training!

Enroll Today


Shawn
Shawn Wildermuth
Author, Teacher, and Coach




My Courses

Wilder Minds Training
Vue.js by Example (Now Available)
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Pluralsight
Less: Getting Started (Coupon Available)
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.1)
Using Visual Studio Code for ASP.NET Core Projects
Implementing ASP.NET Web API
Web API Design

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.27019.06
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86