You can an IMemoryCache
implementation for caching data. There are different implementations of this including an in-memory cache, redis,sql server caching etc..
Quick and simple implemenation goes like this
Update your project.json
file and add the below 2 items under dependencies
section.
"Microsoft.Extensions.Caching.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"
Saving this file will do a dnu restore and the needed assemblies will be added to your project.
Go to Startup.cs class, enable caching by calling the services.AddCaching()
extension method in ConfigureServices
method.
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddMvc();
}
Now you can inject IMemoryCache
to your lass via constructor injection. The framework will resolve a concrete implementation for you and inject it to your class constructor.
public class HomeController : Controller
{
IMemoryCache memoryCache;
public HomeController(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public IActionResult Index()
{
var existingBadUsers = new List<int>();
var cacheKey = "BadUsers";
List<int> badUserIds = new List<int> { 5, 7, 8, 34 };
if(memoryCache.TryGetValue(cacheKey, out existingBadUsers))
{
var cachedUserIds = existingBadUsers;
}
else
{
memoryCache.Set(cacheKey, badUserIds);
}
return View();
}
}
Ideally you do not want to mix your caching within your controller. You may move it to another class/layer to keep everything readable and maintainable. You can still do the constructor injection there.
The official asp.net mvc repo has more samples for your reference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…