title: Why is IMemoryCache's TryGetValue throwing an InvalidOperationException?
body: <p>In my Web application, I have one of my services that uses an injected <code>IMemoryCache</code>:</p>
  
  <pre><code>public class InternalService
  {
      private readonly IMemoryCache m_memoryCache;
  
      private readonly MemoryCacheEntryOptions m_cacheEntryOptions;
  
      public Service(IMemoryCache memoryCache)
      {
           m_memoryCache = memoryCache;
  
           // Set cache options: keep in cache for this time, reset time in 1 hour, no matter what.
          m_cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1d));
      }
  } 
  </code></pre>
  
  <p>In this service, I am using the cache to avoid an expensive call. The call returns a list of Entity:</p>
  
  <pre><code>public class Entity
  {
      public long Id {get; set;}    
  }
  </code></pre>
  
  <p>Here is the method in the Service that deals with the cache:</p>
  
  <pre><code>private async IList&lt;Entity&gt; GetEntitiesAsync(string tenantId)
  {
      if (false == m_memoryCache.TryGetValue(tenantId, out IList&lt;Entity&gt; tenantEntities) || tenantEntities.Count == 0)
      {
           // Do the expensive call.
           IList&lt;Entity&gt; tenantEntities = await ExpensiveServiceCallAsync(tenantId);
  
           m_memoryCache.Set(tenantId, tenantEntities , m_cacheEntryOptions);
      }
  
      return tenantEntities;
  }
  </code></pre>
  
  <p>However, it does throw the following exception:</p>
  
  <blockquote>
    <p>System.InvalidCastException: Unable to cast object of type
    'System.String' to type 'System.Collections.Generic.IList`1[Entity]'. 
    at
    Microsoft.Extensions.Caching.Memory.CacheExtensions.TryGetValue[TItem](IMemoryCache
    cache, Object key, TItem&amp; value)</p>
  </blockquote>
  
  <p>As specified in the Microsoft documentation, it says that :</p>
  
  <blockquote>
    <p>The in-memory cache can store any object; the distributed cache
    interface is limited to byte[].</p>
  </blockquote>
  
  <p><strong>Question</strong></p>
  
  <p>What am I doing wrong? I do not understand why the cache is expecting to return a <code>string</code> when I was supposed to cache a list of <code>Entity</code>. </p>