Asp.Net Core:在控制器外使用内存缓存 [英] Asp.Net Core: Use memory cache outside controller

查看:24
本文介绍了Asp.Net Core:在控制器外使用内存缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET Core 中很容易从控制器访问你的内存缓存

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

在您的启动中添加:

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

然后从您的控制器

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

但是,我如何在控制器之外访问相同的内存缓存.例如.我有一个由 HangFire 启动的计划任务,如何从通过 HangFire 计划任务启动的代码中访问内存缓存?

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可以注入到任何由DI容器控制的组件中;这意味着您需要在 ConfigureServices 方法中配置 ScheduledStuff 实例:

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

并在 ScheduledStuff 构造函数中将 IMemoryCache 声明为依赖项:

and declare IMemoryCache as dependency in ScheduledStuff constructor:

public class ScheduledStuff {
  IMemoryCache MemCache;
  public ScheduledStuff(IMemoryCache memCache) {
    MemCache = memCache;
  }
}

这篇关于Asp.Net Core:在控制器外使用内存缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆