如何使IMemoryCache在所有控制器中可用?

时间:2019-07-11 16:57:09

标签: asp.net-mvc asp.net-core caching asp.net-core-mvc asp.net-core-2.0

我已遵循本教程https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.2

例如,使用依赖注入使[ProtoInclude(4, Whatever)] [ProtoInclude(7, WhateverElse)] class Foo { [ProtoMember(1, ...)] ... [ProtoMember(2, ...)] ... [ProtoMember(3, ...)] ... [ProtoMember(5, ...)] ... [ProtoMember(6, ...)] ... [ProtoMember(8, ...)] ... } 仅在特定控制器中可用

[ProtoInclude(101, Whatever)]
[ProtoInclude(102, WhateverElse)]
class Foo {
   [ProtoMember(1, ...)] ...
   [ProtoMember(2, ...)] ...
   [ProtoMember(3, ...)] ...
   [ProtoMember(4, ...)] ...
   [ProtoMember(5, ...)] ...
   [ProtoMember(6, ...)] ...
}

现在,如果我尝试在相同名称空间或不同控制器中访问IMemoryCache

public class TController : ControllerBase
{
    public IConfiguration Configuration { get; }

    private IMemoryCache _cache;

    public TController(IConfiguration configuration, IMemoryCache memoryCache)
    {
        Configuration = configuration;
        _cache = memoryCache;
    }

    public IActionResult GetAccessToken()
    {

        string key ="IDGKey";
        string obj;
        if (!cache.TryGetValue<string>(key, out obj))
        {
            obj = DateTime.Now.ToString();
            _cache.Set<string>(key, obj);
        }
        return obj;

    }
}

出现以下错误-

  

名称'_cache'在当前上下文中不存在(CS0103)

如何使_cache适用于所有控制器?

1 个答案:

答案 0 :(得分:1)

首先,您需要定义一些使用IMemoryCache

的基本控制器类。
public abstract class MyBaseController : ControllerBase
{
    public IConfiguration Configuration { get; }
    protected IMemoryCache _memoryCache;

    public MyBaseController(IConfiguration configuration, IMemoryCache memoryCache)
    {
        Configuration = configuration;
        _memoryCache = memoryCache;
    }
}

然后从中继承您的控制器,不要忘记调用基类构造函数以实例化IMemoryCache

public class MyController : MyBaseController
{
    public MyController(IConfiguration configuration, IMemoryCache memoryCache): base(configuration, memoryCache)
    {
    }

    public IActionResult Action()
    {
        var value = _memoryCache.Get("some key");
        return Ok();
    }
}