'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



Solution 1:[1]

My answer is focused on the "Does anyone know what the equivalent extension is for HttpRuntime as I cant seem to find it anywhere"


You tagged two different frameworks (.net and .net core), and for them there are two completely different caching implementations/solutions. The first one below is the one you were looking for:

1 - System.Runtime.Caching/MemoryCache
2 - Microsoft.Extensions.Caching.Memory/IMemoryCache


System.Runtime.Caching/MemoryCache:
This is pretty much the same as the old day's ASP.Net MVC's HttpRuntime.Cache. You can use it on ASP.Net CORE without any dependency injection. This is how to use it:

// First install 'System.Runtime.Caching' (NuGet package)

// Add a using
using System.Runtime.Caching;

// To get a value
var myString = MemoryCache.Default["itemCacheKey"];

// To store a value
MemoryCache.Default["itemCacheKey"] = myString;

Microsoft.Extensions.Caching.Memory
This one is tightly coupled with Dependency Injection, and is the recommended way to do it on ASP.Net CORE. This is one way to implement it:

// In asp.net core's Startup add this:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

Using it on a controller:

// Add a using
using Microsoft.Extensions.Caching.Memory;

// In your controller's constructor, you add the dependency on the 'IMemoryCache'
public class HomeController : Controller
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public void Test()
    {
        // To get a value
        string myString = null;
        if (_cache.TryGetValue("itemCacheKey", out myString))
        { /*  key/value found  -  myString has the key cache's value*/  }


        // To store a value
        _cache.Set("itemCacheKey", myString);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vitox