Search code examples
c#cachingconsole-applicationrestsharp.net-6.0

How to setup In memory cache for RestSharp Client in .NET Core Console Application


I have C# console application in .NET 6.

I am researching the setup of a RestSharp client first i need to setup in memory caching. I have done an implementation in asp.net that uses System.Runtime.Caching

Example of the difference :

  public class InMemoryCache : ICacheService
  {
    public T Get<T>(string cacheKey) where T : class
    {
        return MemoryCache.Default.Get(cacheKey) as T;
    }

the MemoryCache.Default is not part of the Extension Library Microsoft.Extensions.Caching.Memory like the However with the console application with .NET 6 I have to use Microsoft.Extensions.Caching.Memory

How would i implement the above with using Microsoft.Extensions.Caching.Memory

Also here is my configuration

 //class Program
 private static InMemoryCache _cache;

 //Main

 services.AddMemoryCache();
 var serviceProvider = services.BuildServiceProvider();
 _cache = serviceProvider.GetService<InMemoryCache>();

Solution

  • If you want your own wrapper around IMemoryCache - you should inject IMemoryCache into InMemoryCache and use it (InMemoryCache should also be registered in the DI as InMemoryCache so you can resolve it):

    public class InMemoryCache : ICacheService
    {
        private readonly IMemoryCache _cache;
    
        public InMemoryCache(IMemoryCache cache)
        {
            _cache = cache;
        }
        public T Get<T>(string cacheKey) where T : class
        {
            return _cache.Get<T>(cacheKey);
        }
    }