Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core: Use memory cache outside controller

In ASP.NET Core its very easy to access your memory cache from a controller

In your startup you add:

public void ConfigureServices(IServiceCollection services)
        {
             services.AddMemoryCache();
        }

and then from your controller

[Route("api/[controller]")]
public class MyExampleController : Controller
{
    private IMemoryCache _cache;

    public MyExampleController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    [HttpGet("{id}", Name = "DoStuff")]
    public string Get(string id)
    {
        var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1));
        _cache.Set("key", "value", cacheEntryOptions);
    }
}

But, how can I access that same memory cache outside of the controller. eg. I have a scheduled task that gets initiated by HangFire, How do I access the memorycache from within my code that starts via the HangFire scheduled task?

public class ScheduledStuff
{
    public void RunScheduledTasks()
    {
        //want to access the same memorycache here ...
    }
}
like image 257
SpeedBird527 Avatar asked Feb 05 '17 07:02

SpeedBird527


3 Answers

There is another very flexible and easy way to do it is using System.Runtime.Caching/MemoryCache

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, in any class you want to. 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;
like image 182
Vitox Avatar answered Sep 21 '22 09:09

Vitox


Memory cache instance may be injected to the any component that is controlled by DI container; this means that you need configure ScheduledStuff instance in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services) {
  services.AddMemoryCache();
  services.AddSingleton<ScheduledStuff>();
}

and declare IMemoryCache as dependency in ScheduledStuff constructor:

public class ScheduledStuff {
  IMemoryCache MemCache;
  public ScheduledStuff(IMemoryCache memCache) {
    MemCache = memCache;
  }
}
like image 9
Vitaliy Fedorchenko Avatar answered Oct 19 '22 18:10

Vitaliy Fedorchenko


I am bit late here, but just wanted to add a point to save someone's time. You can access IMemoryCache through HttpContext anywhere in application

var cache = HttpContext.RequestServices.GetService<IMemoryCache>();

Please make sure to add MemeoryCache in Startup

services.AddMemoryCache();
like image 8
Thakur Avatar answered Oct 19 '22 17:10

Thakur