I tired setting a populated IReadOnlyList to cache but it was always null:
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
MemoryCache.Default.Set(_cacheKey, dataList, cip);
}
Nothing is set in Cache. But if I change it to:
List<T> list = null;
CacheItemPolicy cip = new CacheItemPolicy(); // no expiration
IReadOnlyList<T> dataList = [populate var]
if (dataList != null)
{
list = dataList.ToList();
MemoryCache.Default.Set(_cacheKey, list, cip);
}
it works. Does MemoryCache not support interfaces or the IReadOnlyList object?
MemoryCache is caching the reference to the list in the first example and a copy of the list in the second example.
It must be your code is reusing the list passed in as dataList and so you require a copy to be cached. Calling ToList() makes a copy.