Reputation: 115
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."
Upvotes: 2
Views: 6073
Reputation: 53600
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.
Upvotes: 5