简体   繁体   中英

How to disable MemoryCache in Entity Framework Core?

I have this code on my Startup.

var connection = Configuration.GetConnectionString("DefaultConnection")?.Replace("[BD_PASS]", Environment.GetEnvironmentVariable("BD_PASS"));
services.AddDbContext<BdContext>(options => options.UseSqlServer(connection));

services.AddMemoryCache(op =>
            {
                op.SizeLimit = int.Parse(Environment.GetEnvironmentVariable("CACHE_SIZE_LIMIT") ?? "10");
            });

The problem is that I wasn't aware that Entity Framework Core would intercept my queries against the database. So, I am getting a

 _context.Product.ToList();

But I am getting this message when the code above is run.

cache entry must specify a value for size when the size limit is set

Is there anything I could do at the configuration level to say "Hey EFC, don't you bother to cache anything."

Entity Framework Core uses what's called the "shared cache". It depends on IMemoryCache registered in the service container. The solution isn't to stop EF Core from using a cache, it's to use a different cache for your services that understand cache size limits.

In other words, create a tailored cache for your own use:

public class LimitedMemoryCache 
{
    public MemoryCache Cache { get; private set; }

    public LimitedMemoryCache(int limit)
    {
        Cache = new MemoryCache(new MemoryCacheOptions
        {
            SizeLimit = 10
        });
    }
}

And register it as a separate singleton:

var cacheLimit = int.Parse(Environment.GetEnvironmentVariable("CACHE_SIZE_LIMIT") ?? "10");
services.AddSingleton(new LimitedMemoryCache(cacheLimit));

Classes can choose to use this cache by injecting LimitedMemoryCache instead of IMemoryCache . Entity Framework Core and anything else that depends on IMemoryCache directly can now coexist without any problems.

This is mentioned on the in-memory cache docs , which is how I learned about it myself:

... When a size limit is set on a cache, all entries must specify a size when being added. This can lead to issues since developers may not have full control on what uses the shared cache. For example, Entity Framework Core uses the shared cache and does not specify a size. If an app sets a cache size limit and uses EF Core, the app throws an InvalidOperationException. When using SetSize, Size, or SizeLimit to limit cache, create a cache singleton for caching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM