Caching entity itself in IMemoryCache in ASP.NET Core MVC with Entity Framework

asp.net-core-mvc caching entity-framework-core

Question

In an ASP.NET Core MVC app I'm using IMemoryCache in ConfigureServices():

services.AddMemoryCache();

In a controller, I originally had this code:

// List<> of POCOs:
var myLines = await _context.MyEntity.Where(somecondition).ToListAsync();

and I've changed it to:

// List<> of POCOs:
var myLines = await
    _cache.GetOrCreateAsync("mykey",async entry => {
        return
            await _context.MyEntity.Where(somecondition).ToListAsync();
    });

This works well.

But I'm wondering if it is a bad practice anyway or not.

Is it a problem caching attached POCOs?

1
0
4/15/2020 8:05:21 PM

Accepted Answer

This i very basic usage of memory cache, it can meet some basic requirement, but please consider below senario

  1. Your POCO is changed by someone else, how would your cache know that? You'll need some sync task to sync your cache and database data
  2. Your application is going to be delpoyed to a web farm, memery cache only works for just one machine, a request routed to another machine won't have the cache. In this senario you'll need a out of process cache such as redis or even build your own distributed cache.

So it really depends on what is your requirement, if it is simple enough, than this approach is a good practice. Otherwise you need to take the above 2 senario into consideration since these 2 are the most common issue for a cache solution.

1
4/16/2020 10:10:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow