【问题标题】:In-Memory Cache with .NET EF Core throws error带有 .NET EF Core 的内存缓存抛出错误
【发布时间】:2021-12-25 07:36:37
【问题描述】:

我有一个带有 EF 的 .Net Core 应用程序,它返回一个名为 Customer 的页面作为主页。但是当用户尝试在假期访问应用程序(假期列表存储在表格中)而不是客户页面时,我需要显示一个应用程序不可用页面(AppNotAvialable.cshmtl)。我不是每次访问主页时都查询假期列表表,而是尝试使用内存缓存,以便我可以将查询响应存储在缓存中并在控制器中使用它们。我是第一次实现缓存,下面是我尝试过的

public class CustomersController : Controller
   {
      private readonly SurplusMouseContext _context;
      private readonly IMemoryCache memoryCache;

       .......................

  public async Task<IActionResult> Index(string sortOrder, string searchString,
                                           int? pageNumber, string currentFilter)
    {
        int holidaycheck;
        var timeUtc = DateTime.UtcNow;
        var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
        var todayDt = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);

        bool isExist = memoryCache.TryGetValue("HolidayWk", out holidaycheck);
        if (!isExist)
        {
            holidaycheck = (from hc in _context.HolidayWeeks
                            where hc.HolidateDate.Date == todayDt.Date
                            select hc).Count();
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromHours(2));

            memoryCache.Set("HolidayWk", holidaycheck, cacheEntryOptions);
        }

        if (holidaycheck != 0)
        {
            return View("/Views/Customers/AppNotAvailable.cshtml");
        }
        else
        {

当我尝试调试应用程序时,它会抛出如下错误

任何人都可以建议我是否在这里实现内存缓存正确/遗漏任何东西以及我应该在哪里做cacheMemory.Remove()任何帮助非常感谢

【问题讨论】:

  • 你实例化MemoryCache实例了吗?
  • 你是不是在startup.cs中绑定了对象,然后在构造函数中使用?

标签: asp.net-core .net-core caching entity-framework-core asp.net-core-mvc


【解决方案1】:

第一步检查:

在您的问题中,您可能没有在构造函数中初始化 MemoryCache 对象。


MemoryCache的例子。

1 - 你应该在这样的服务中注册MemoryCache

services.AddMemoryCache();

2 - 在控制器中注入IMemoryCache 接口并对其进行初始化。

public class YourController : Controller
{
    private readonly IMemoryCache _memoryCache;
    public YourController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache
    }
}

3 - 使用内存缓存:

public async Task<IActionResult> Index(string sortOrder, string searchString,
                                           int? pageNumber, string currentFilter)
{
    bool isExist = _memoryCache.TryGetValue("HolidayWk", out holidaycheck);
}

【讨论】:

  • 谢谢!!!!我们如何/在哪里清除 cacheMemory.Remove()
猜你喜欢
  • 2018-03-07
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2020-11-23
  • 2018-08-18
相关资源
最近更新 更多