.NET 6 Display MemoryCache values – 3

Previosly we have mentioned about MemoryCache basics, after that we have implemented MemoryCahe by including some business scenarios.

This time let’s create a controller and get MemoryCache values by giving cache’s key!

I am going to use CacheBase.cs (which we have created at second article, you can take it from there)

public class CacheBase<TEntity> where TEntity : class
{
    private readonly string key = typeof(TEntity).Name; // need a custom name to register cachename
    private MemoryCacheEntryOptions options { get; set; }
    private readonly IMemoryCache _cache;

    public CacheBase(IMemoryCache cache) // resolve from IoC 
    {
        _cache = cache;
        ReloadCache();
    }

    protected virtual MemoryCacheEntryOptions SetPolicy() // override will decide policy
    {
        return null;
    }

    protected virtual List<TEntity> GetEntityList() // override will decide the objects
    {
        return null;
    }
    public void ReloadCache()
    {
        IEnumerable<TEntity> tempList = GetEntityList();
        options = SetPolicy();
        _cache.Set(key, tempList, options); // this will add our 3 items to cache with ConfigurationCache key
    }

    public bool TryGetList(out List<TEntity> valueList)
    {
        valueList = (List<TEntity>)_cache.Get(key);

        if (options != null && options.AbsoluteExpiration < DateTime.Now) // if expired
        {
            ReloadCache(); // try load our 3 items again

            if (!TryGetList(out valueList)) // try select from cache again
            {
                return false; // if it is failed we can't do anything more
            }
        }

        return valueList != null;
    }
}

And lets create a CacheController

[ApiController]
[Route("api/[controller]")]
public class CacheController : ControllerBase
{
    protected readonly IServiceProvider provider;

    public CacheController(IServiceProvider provider)
    {
        this.provider = provider;
    }

    [HttpGet]
    public IActionResult Get(string key)
    { 
        string typeName = $"WebApplication3.{key}"; // replace namespace with yours
        Type type = Type.GetType(typeName);
        if (type == null)
        {
            return null;
        }

        dynamic service = provider.GetService(type);
        return service.GetList();
    }
}

There is a Get method which takes key as input. Also you can see that there is a GetList() method to access cache values. We need to add this method t our CacheBase class like below,

public List<TEntity> GetList()
{
    TryGetList(out List<TEntity> result);
    return result;
}

1- First it found the Cache object

2- It resolved it’s dependency from IoC

3- Invoked GetList method from CacheBase

Let’s see it’s working,

Cool 🙂