Using StackExchange.Redis in a ASP.NET Core Controller

I prefer to use username/password in the configuration

//StackExchange.Redis for configuration options
 var redisConfiguration = new ConfigurationOptions
                EndPoints = { "serverinfo:portinfo" },
                User = username,
                Password = password
                //,Ssl = true

            services.AddStackExchangeRedisCache(options => { options.ConfigurationOptions = redisConfiguration; });

This blog has a writeup (with accompanying full code repo) about implementing a redis service into ASP.NET Core. It has a boilerplate service that automatically serialises POCO classes into a redis hashset.

The simple way is to install the Nuget package

Install-Package Microsoft.Extensions.Caching.Redis 

in your ASP MVC .NET Core project.

Then configure the service with dependency injection in your class Startup in the method ConfigureServices:

        services.AddDistributedRedisCache(option =>
            option.Configuration = Configuration["AzureCache:ConnectionString"];
            option.InstanceName = "master";

Add the binding connection string in the appsettings.json for release deployment like this:

"AzureCache": {
    "ConnectionString": "" 

If you use Azure, add in the App setting name in Application Settings for your ASP MVC .NET Core App Service to bind at run-time on the Azure side after deployment. The connection string for production shouldn't occur in your code from the security reasons.

Azure binding connection string

Add the binding for e.g. development appsettings.Development.json

"AzureCache": {
    "ConnectionString": "<your connection string>"

Inject the service to your controller in the constructor:

public class SomeController : Controller
        public SomeController(IDistributedCache distributedCache)

In your Startup class's ConfigureServices method, you'll want to add:


You can then use the dependency injection by changing your constructor signature to something like this:

public YourController : Controller
    private readonly IConnectionMultiplexer _connectionMultiplexer;
    public YourController(IConnectionMultiplexer multiplexer)
        this._connectionMultiplexer = multiplexer;