Asp.Net Core: Use memory cache outside controller

2019-03-27 18:47发布

问题:

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

回答1:

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


回答2:

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