简体   繁体   中英

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

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;
  }
}

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM