I have a wrapper class for Memory cache, its rather straight forward and lets me just set some defaults. However, I noticed that during my regression tests, that the .Remove method from memory cache does not work 100% of the time.
I'm wondering if anyone is aware of some bug with it or maybe my wrapper is causing the problem potentially? I don't see how though. If I run the regression test I have in place it will fail and then on next run without any code changes it succeeds. When I debug I found that it was because the cache was not refreshed. Basically the item I put in the cache still had the value from first time it was inserted.
The logic goes like this:
//insert record to database
//create cache
//insert second record to database
//remove cache
//create new cache
Has anyone encountered a problem like this?
internal class CacheService : ICacheService
{
private readonly IMemoryCache _memoryCache;
private const int DefaultCacheDuration = 3600;
public CacheService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public void Create(string? key, object? value, int durationInMinutes)
{
if (string.IsNullOrWhiteSpace(key) || value == null) return;
if (durationInMinutes <= 0) durationInMinutes = DefaultCacheDuration;
_memoryCache.Set(key, value, TimeSpan.FromMinutes(durationInMinutes));
}
public T? Get<T>(string? key)
{
if (string.IsNullOrWhiteSpace(key))
{
return default;
}
return _memoryCache.TryGetValue<T>(key, out var value) ? value : default;
}
public void Remove(string? key)
{
if (!string.IsNullOrWhiteSpace(key))
{
_memoryCache.Remove(key);
}
}
}
Note: The cache key is a constant value so its not getting caught by null checks.
Edit:
ICacheService is injected under DependencyInjectionScope.Transient scope.
The regression test is one long test so the cache when it is setup, it is only setup once and the injection gets it from the same pool.
The entire test is on a single thread and I never call MemoryCache.Clear()
The problem you mentioned is that, in the first execution, the memory cache is empty because the key in the memory cache only receives a value after the first execution.