内存缓存 .Net Core 不持久值

Memory Cache .Net Core Not Persisting Values

我有一个 .NET Core 2.1 应用程序。在Startup.cs配置方法中,我使用:

services.AddDbContext<ApplicationDbContext>(options =
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...

services.AddMemoryCache();   

然后在我的控制器中:

public class DropDownListController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly IMemoryCache _memoryCache;

    private const string ProvidersCacheKey = "providers";
    private const string AgenciesCacheKey = "agencies";

    public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
    {
        _context = context;
        _memoryCache = memoryCache;
    }
}

并且在控制器中,获取下拉列表的方法:

public JsonResult GetProvider()
{
    IEnumerable<DropDownListCode.NameValueStr> providerlist;

    if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
    {
        return Json(providerlist);
    }
    else
    {
        MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
        cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
        cacheExpirationOptions.Priority = CacheItemPriority.Normal;

        DropDownListCode um = new DropDownListCode(_context);
        var result = um.GetProviderList();

        _memoryCache.Set(ProvidersCacheKey, result);

        return Json(result);
    }
}

当我在行上设置断点时:

return Json(providerlist);

我看到 ProvidersCacheKey_memoryCache 中,但它没有任何价值。

数据怎么了?

当我在 _memoryCache 上进行快速观察时,我可以看到 DbContext 对象已被销毁。但是怎么会呢,代码可以正常运行,但是缓存对象中没有我保存的数据。

如有任何帮助,我们将不胜感激。

获取供应商的方法是:

public IEnumerable<NameValueStr> GetProviderList()
    {
        var providerlist = (from a in _context.AgencyProvider
                            where a.Provider == a.AgencyId
                            select new NameValueStr
                            {
                                id = a.Provider,
                                name = a.Name
                            });

        return providerlist.Distinct();
    }

在调用方法中添加 "ToList()" 有效:

MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
            cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
            cacheExpirationOptions.Priority = CacheItemPriority.Normal;
            DropDownListCode um = new DropDownListCode(_context);
            var result = um.GetProviderList().ToList();
            _memoryCache.Set(ProvidersCacheKey, result);
            return Json(result);

所有功劳都归功于 Steve Py……谢谢先生!