22

I'd like to use Redis features such as bitfields and hashfields from an MVC controller. I understand there's built in caching support in ASP.NET core but this only supports basic GET and SET commands, not the commands that I need in my application. I know how to use StackExchange.Redis from a normal (eg. console) application, but I'm not sure how to set it up in an ASP site.

Where should I put all the connection initialization code so that I can have access to it afterwards from a controller? Is this something I would use dependency injection for?

John Smith
  • 7,243
  • 6
  • 49
  • 61
Naarkie
  • 351
  • 1
  • 2
  • 10

4 Answers4

46

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

services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("yourConnectionString"));

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;
    }
}
John Smith
  • 7,243
  • 6
  • 49
  • 61
Trey Dibler
  • 561
  • 4
  • 4
10

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.

Naarkie
  • 351
  • 1
  • 2
  • 10
4

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)
Ondrej Rozinek
  • 563
  • 8
  • 14
  • 4
    This looks pretty and all, but keep in mind that this only implements a `IDistributedCache` which is a very limited implementation of Redis. More info here: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2 – Andy Apr 29 '19 at 12:58
1

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; });
  • 1
    It's worth noting that it's not usually considered a good practice to store a username and password in clear text directly in your code, and especially if your code is (hopefully!) managed via source control, as that opens up a potential vulnerability in case your code is compromised. The previous [answer from @Ondrej-Rozinek](https://stackoverflow.com/a/53004428/3025856) addresses this by instead storing the credentials in a separate configuration file—which could be a `secrets.json` locally, an environment variable on a server, or any other configuration provider supported by ASP.NET Core. – Jeremy Caney Oct 27 '20 at 22:36
  • Yes, its good to store encrypted credentials in separate file. I was mentioning user username/password key pair. Redis ACL has option to encrypt password and all the configuration:) Its best practice to use username/password With ssl enable instead just having server and password or default user. – umesh maharjan Oct 29 '20 at 16:13
  • Aha, I see what you're saying. Thank you for clarifying that. – Jeremy Caney Oct 29 '20 at 20:52