HttpRuntime.Cache Equivalent for asp.net 5, MVC 6

核能气质少年 提交于 2019-11-29 15:34:14

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!