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?
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;
}
}
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)
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With