Search code examples
asp.net-core.net-corecachingentity-framework-coreasp.net-core-mvc

In-Memory Cache with .NET EF Core throws error


I have a .Net Core application with EF which returns a page called Customer as home page. But I need show an app not available page (AppNotAvialable.cshmtl) when the user tries to access the application on a holiday(holiday list is stored in a table)instead of the Customer page. Instead of querying the holiday list table every time the home page is accessed I am trying to use the In-Memory Cache so I can store the query response in cache and use them in the controller. I am implementing the cache for the 1st time and below is what I tried

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
        {

when I try to debug the application it throws error like below

enter image description here

Can anyone please suggest if I am implementing the in Memory Cache here correct/missing anything and where should I be doing the cacheMemory.Remove() Any help is greatly appreciated


Solution

  • The first step to check:

    In your question, it is possible you didn't initialize MemoryCache object in the constructor.


    There is an example of MemoryCache.

    1 - You should register MemoryCache in services like this:

    services.AddMemoryCache();
    

    2 - Inject IMemoryCache interface in your controller and initialize it.

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

    3 - Using memory cache:

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