0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a simplified sample code; changing underlying data is tracked by some other code lines. Yes, I know this works for one server, that's not a problem in my case. I worried for attached 'state' of POCOs mostly. Thanks anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.