问题
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 initialisation code so that I can have access to it afterwards from a controller? Is this something I would use dependency injection for?
回答1:
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 IConnectionMultiplexer _connectionMultiplexer;
public YourController(IConnectionMultiplexer multiplexer)
{
this._connectionMultiplexer = multiplexer;
}
}
回答2:
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.
回答3:
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)
来源:https://stackoverflow.com/questions/46368234/using-stackexchange-redis-in-a-asp-net-core-controller