13

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 ...
    }
}
SpeedBird527
  • 149
  • 2
  • 4
  • 18

3 Answers3

9

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;
  }
}
Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34
  • Thanks for your help Vitaliy. The problem now is, how can I kick off the RunScheduledTasks method? It requires the memoryCache parameter. Error CS7036 There is no argument given that corresponds to the required formal parameter 'memoryCache' of 'ScheduledStuff.ScheduledStuff(IMemoryCache)' `ScheduledStuff scheduledStuff = new ScheduledStuff();` <- Error here `scheduledStuff.RunScheduledTasks();` – SpeedBird527 Feb 07 '17 at 11:58
  • 2
    you shouldn't create `SheduledStuff` instance in your code, instead of this you need to get it from DI container - by defining it as dependency in Controller, or with `HttpContext.RequestServices`. – Vitaliy Fedorchenko Feb 07 '17 at 14:15
9

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();
Thakur
  • 559
  • 6
  • 15
  • 2
    Getting error when using HttpContext.RequestServices.GetService(); : An object reference is required for the non static field, method or property. – Sunny Nov 23 '19 at 13:08
  • HttpContext isnt available _everywhere_. This will only work in a controller, or something with a context. – CarComp Mar 15 '22 at 13:13
3

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;
Vitox
  • 3,852
  • 29
  • 30