'Net Core MemoryCache not resetting per request

.Net Core 3.0. I have a repo where IMemoryCache gets injected. Repo is registered as Transient. I would like for the cache to be cleared/reset PER request, however that is not happening. It keeps data inserted there from prev request. How do I make it so that MemoryCache is re-created per request?

public OrganizationRepository(
   IMemoryCache cache)
{
    m_cache = cache;
    // cache still has data in entries for subsequent requests
}

Registrations:

services.AddTransient<IOrganizationRepository, OrganizationRepository>();


Solution 1:[1]

This seems to work:

services.AddScoped<MemoryCache, MemoryCache>();

then inject it as MemoryCache

Solution 2:[2]

You can write your own memory cache easily.

private readonly Dictionary<string, List<Product>> _localCache = new Dictionary<string, List<Product>>();

public async Task<List<Product>> LocalListAsync(bool invalidateCache = false)
{
    const string cacheKey = "ProductList";
    if (invalidateCache)
    {
        _localCache.Remove(cacheKey);
    }

    if (_localCache.TryGetValue(cacheKey, out var list))
    {
        return list;
    }

    await _products
        .Include(x => x.ProductCategory)
        .LoadAsync();

    list = _products.Local.ToList();
    _localCache.Add(cacheKey, list);
    return list;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ShaneKm
Solution 2 alireza etemadi