Azure Cache in ASP.NET Core 2.0

Problem

How to use Azure Redis cache in ASP.NET Core.

Solution

Create a class library and add NuGet packages:

  • StackExchange.Redis
  • Newtonsoft.Json

Add a class to encapsulate settings:

Add a class for cache storage. Add a constructor and private methods to initialise the Azure client:

Now methods to access the cache:

Inject and use the class:

In ASP.NET Core Web Application, configure services:

Discussion

The sample code will require you to setup Azure account and Redis cache. Instructions for these could be found at: https://docs.microsoft.com/en-gb/azure/redis-cache/cache-dotnet-how-to-use-azure-redis-cache#create-cache

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Azure.Cache

2 comments

    1. Thanks, glad it helped. There is a KeyExpire() method on IDatabase where you can set the expiry of a key. Feel free to fork my GitHub repo, make the change to extend with this functionality and send me a pull request 🙂

Leave a Reply