When starting my application, I'm loading many configuration parameters into the MemoryCache and I can confirm that after doing that (in the Startup.cs), that there are about 280 entries inside of the cache.
When I inject a IMemoryCache into a controller and return all the entries as json, there are suddenly only 16 items inside and they are none of the ones that I loaded initially.
What could be reasons that this is happening? I was looking for places where the cache could be cleared but didn't find any. Is the IMemoryCache not implemented as a singleton?
In the Startup.ConfigureServices I'm adding the memory cache as one of the first statements:
services.AddMemoryCache();
I'm loading the items initially like this:
var spp = services.BuildServiceProvider().GetRequiredService<ISysParamProvider<IDbContext>>();
spp.LoadAll();
Could the problem be, that a new ServiceProvider is built here? If so, how can I get the ISysParamProvider instance instead?
Do I have to consider anything else so that I will get this instance injected into the controller?
Thanks in advance
The LoadAll()-method looks like this:
public async Task LoadAll()
{
var sysParams= this.db.Set<SysParam>().ToList();
foreach (var sysParam in sysParams)
{
if (!this.cache.TryGetValue(sysParam.ParamName, out _))
{
var cacheentryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromDays(1));
this.cache.Set(sysParam.ParamName, sysParam.ParamValue, cacheentryOptions);
}
}
}
CodePudding user response:
The problem was indeed with the services.BuildServiceProvider().GetRequiredService<ISysParamProvider<IDbContext>>();
as it seemed to have created another instance of the IMemoryCache (which is injected in the ISysParamProvider).
The solution to this was to inject the ISysParamProvider
into the Configure
method of the Startup and fill the cache there via spp.LoadAll()
. By doing that, the correct IMemoryCache
was injected into ISysParamProvider
.