【问题标题】:Asp.Net Core: Use memory cache outside controllerAsp.Net Core:在控制器外使用内存缓存
【发布时间】:2017-06-22 07:40:45
【问题描述】:

在 ASP.NET Core 中,从控制器访问内存缓存非常容易

在您的启动中添加:

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 计划任务启动的代码中访问内存缓存?

public class ScheduledStuff
{
    public void RunScheduledTasks()
    {
        //want to access the same memorycache here ...
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-core .net-core memorycache


    【解决方案1】:

    内存缓存实例可以注入到任何受DI容器控制的组件中;这意味着您需要在ConfigureServices 方法中配置ScheduledStuff 实例:

    public void ConfigureServices(IServiceCollection services) {
      services.AddMemoryCache();
      services.AddSingleton<ScheduledStuff>();
    }
    

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

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

    【讨论】:

    • 感谢您的帮助 Vitaliy。现在的问题是,如何启动 RunScheduledTasks 方法?它需要 memoryCache 参数。错误 CS7036 没有给出与“ScheduledStuff.ScheduledStuff(IMemoryCache)”ScheduledStuff scheduledStuff = new ScheduledStuff(); 的所需形式参数“memoryCache”相对应的参数
    • 您不应该在代码中创建 SheduledStuff 实例,而是需要从 DI 容器中获取它 - 通过将其定义为 Controller 中的依赖项或使用 HttpContext.RequestServices
    【解决方案2】:

    我在这里有点晚了,但只是想补充一点以节省某人的时间。您可以在应用程序的任何地方通过 HttpContext 访问 IMemoryCache

    var cache = HttpContext.RequestServices.GetService<IMemoryCache>();
    

    请确保在启动时添加 MemeoryCache

    services.AddMemoryCache();
    

    【讨论】:

    • 使用 HttpContext.RequestServices.GetService() 时出错; : 非静态字段、方法或属性需要对象引用。
    • HttpContext 不可用无处不在。这仅适用于控制器或具有上下文的东西。
    【解决方案3】:

    还有另一种非常灵活且简单的方法是使用System.Runtime.Caching/MemoryCache

    System.Runtime.Caching/MemoryCache:
    这与过去的 ASP.Net MVC 的HttpRuntime.Cache 几乎相同。 您可以在 ASP.Net CORE 上使用它而无需任何依赖注入,在任何您想要的类中。使用方法如下:

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

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2019-04-24
      相关资源
      最近更新 更多