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 ...
    }
}
0

3 Answers 3

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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();
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.
8

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();

3 Comments

Getting error when using HttpContext.RequestServices.GetService<IMemoryCache>(); : An object reference is required for the non static field, method or property.
HttpContext isnt available everywhere. This will only work in a controller, or something with a context.
misleading response. It is not accessible 'anywhere' throughout the 'application'.
4

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.