Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So I've just moved from ASP.Net 4 to ASP.Net 5. Im at the moment trying to change a project so that it works in the new ASP.Net but of course there is going to be a load of errors.

Does anyone know what the equivalent extension is for HttpRuntime as I cant seem to find it anywhere. I'm using to cache an object client side.

HttpRuntime.Cache[Findqs.QuestionSetName] 

'Findqs' is just a general object

like image 686
Alex Grogan Avatar asked Dec 22 '15 10:12

Alex Grogan


1 Answers

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 class 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.

like image 92
Shyju Avatar answered Nov 11 '22 04:11

Shyju