35

I am trying to write a class to handle Memory cache in a .net core class library. If I use not the core then I could write

using System.Runtime.Caching;
using System.Collections.Concurrent;

namespace n{
public class MyCache
{
        readonly MemoryCache _cache;
        readonly Func<CacheItemPolicy> _cachePolicy;
        static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();

        public MyCache(){
            _cache = MemoryCache.Default;
            _cachePolicy = () => new CacheItemPolicy
            {
                SlidingExpiration = TimeSpan.FromMinutes(15),
                RemovedCallback = x =>    
                {
                    object o;
                    _theLock.TryRemove(x.CacheItem.Key, out o);
                }
            };
        }
        public void Save(string idstring, object value){
                lock (_locks.GetOrAdd(idstring, _ => new object()))
                {
                        _cache.Add(idstring, value, _cachePolicy.Invoke());
                }
                ....
        }
}
}

Within .Net core I could not find System.Runtime.Cache. After reading the .net core In Memory Cache, I have added reference Microsoft.Extensions.Caching.Memory (1.1.0) and tried

using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Memory;

namespace n
{
    public class MyCache
    {
            readonly MemoryCache _cache;
            readonly Func<CacheItemPolicy> _cachePolicy;
            static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();
            public MyCache(IMemoryCache memoryCache){
                   _cache = memoryCache;// ?? **MemoryCache**; 
            }

            public void Save(string idstring, object value){
                    lock (_locks.GetOrAdd(idstring, _ => new object()))
                    {
                            _cache.Set(idstring, value, 
                              new MemoryCacheEntryOptions()
                              .SetAbsoluteExpiration(TimeSpan.FromMinutes(15))
                              .RegisterPostEvictionCallback(
                                    (key, value, reason, substate) =>
                                    {
                                        object o;
                                        _locks.TryRemove(key.ToString(), out o);
                                    }
                                ));
                    }
                    ....
            }
    }
}

Hope code inside the save method is ok, although most of my mycache tests are failing at the moment. Can anyone please point out what is wrong? The main question is about the constructor What should i do to set the cache instead MemoryCache.Default

_cache = memoryCache ?? MemoryCache.Default; 

4 Answers 4

78

The constructor is:

using Microsoft.Extensions.Caching.Memory;

. . .

MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());
3
  • 1
    In this method we could not achieve memory cache behavior in NET standard library. Can you please how to integrate IMemorycache in NET Standard library?
    – Parthi
    Commented Jul 5, 2019 at 12:37
  • @Parthi Read this thread please: github.com/aspnet/AspNetCore.Docs/issues/7556 Commented Jul 10, 2019 at 8:17
  • @mattinsalto How to set memory cache name?
    – Tomas
    Commented Jan 27, 2020 at 11:53
35

My answer is focused on the "Within .Net core I could not find System.Runtime.Cache", as I run into this same issue. For using IMemoryCache with the specific OP's scenario, the accepted answer is great.


There are two completely different caching implementations/solutions:

1 - System.Runtime.Caching/MemoryCache
2 - Microsoft.Extensions.Caching.Memory/IMemoryCache


System.Runtime.Caching/MemoryCache:
This is pretty much the same as the old day's ASP.Net MVC's HttpRuntime.Cache. You can use it on ASP.Net CORE without any dependency injection. This is how to use it:

// First install 'System.Runtime.Caching' (NuGet package)

// Add a using
using System.Runtime.Caching;

// To get a value
var myString = MemoryCache.Default["itemCacheKey"];

// To store a value
MemoryCache.Default["itemCacheKey"] = myString;

Microsoft.Extensions.Caching.Memory
This one is tightly coupled with Dependency Injection. This is one way to implement it:

// In asp.net core's Startup add this:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

Using it on a controller:

// Add a using
using Microsoft.Extensions.Caching.Memory;

// In your controller's constructor, you add the dependency on the 'IMemoryCache'
public class HomeController : Controller
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public void Test()
    {
        // To get a value
        string myString = null;
        if (_cache.TryGetValue("itemCacheKey", out myString))
        { /*  key/value found  -  myString has the key cache's value*/  }


        // To store a value
        _cache.Set("itemCacheKey", myString);
    }
}

As pointed by @WillC, this answer is actually a digest of Cache in-memory in ASP.NET Core documentation. You can find extended information there.

6
  • 2
    Thanks for the info. I was porting some code from .net to core and this is useful as the two overlapping implementations are confusing.
    – WillC
    Commented Sep 30, 2020 at 14:34
  • I also found this link to expand on what you are saying here. learn.microsoft.com/en-us/aspnet/core/performance/caching/…
    – WillC
    Commented Sep 30, 2020 at 14:37
  • @WillC I'm very glad that this answer helped you! Yes, the link you provided actually was my source to execute these implementations. My answer is kinda "digest" from the very same documentation you provided. I thought it would be unnecessary, but since it was relevant to you, I'll include it on my answer.
    – Vitox
    Commented Sep 30, 2020 at 18:35
  • 1
    @LeiYang Good question. That depends on some factors: If you're already working with Dependency Injection, you can easily implement together with your other dependencies the Microsoft.Extensions.Caching.Memory/IMemoryCache. Also, if you are working with ASP.Net Core, it's kind of best practice to use DI. On the other hand, if your use is specific, simple and limited, I don't see any design problem on using System.Runtime.Caching/MemoryCache. And also, the latter would be extremely helpful for prototyping.
    – Vitox
    Commented Jun 1, 2021 at 5:34
  • 1
    @LeiYang Resuming it's a design aspect. I would say that it's the same answer when questioning "when should I use Dependency Injection". I should also mention that the new Microsoft.Extensions.Caching.Memory/IMemoryCache is a "updated" and current version of System.Runtime.Caching/MemoryCache that is only supported right now as a legacy solution. So IMemoryCache has a better performance, but actually the performance difference is absolutely negligible for the vast majority of cases.
    – Vitox
    Commented Jun 1, 2021 at 5:43
5
  • Inject MemoryCache Through constructor (get the reference from nugget Microsoft.Extensions.Caching.Memory)
 private readonly IMemoryCache memoryCache;
  • Code Implementation
 private IList<Employee> GetListFromCache()
        {
            const string Key = "employee";
            IList<Employee> cacheValue = null;
            if (!this.memoryCache.TryGetValue(Key, out cacheValue))
            {
                //// Key not in cache, so get data.
                cacheValue = this.context.Employee.AsNoTracking().Include(x => 
                x.Id).ToList();
                       
                //// Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    //// Keep in cache for this time, reset time if accessed.
                    .SetSlidingExpiration(TimeSpan.FromDays(1));

                //// Save data in cache.
                this.memoryCache.Set(Key, cacheValue, cacheEntryOptions);
            }

            return cacheValue;
        }

Register AddMemoryCache under ConfigureServices in Startup.cs

 services.AddMemoryCache();
  • Mock IMemoryCache for Unit Test
     /// <summary>Gets the memory cache.</summary>
        /// <returns> Memory cache object.</returns>
        public IMemoryCache GetMemoryCache()
        {
            var services = new ServiceCollection();
            services.AddMemoryCache();
            var serviceProvider = services.BuildServiceProvider();

            return serviceProvider.GetService<IMemoryCache>();
        }

//Inject memory cache in constructor for unit test
  this.memoryCache = text.GetMemoryCache();
2

If you using Asp.net core you no need to custom SingleTon for cache, because Asp.net core is supported DI for your Cache class.

To using IMemoryCache to set data to the memory of the server you can do as below:

public void Add<T>(T o, string key)
{
    if (IsEnableCache)
    {
        T cacheEntry;

        // Look for cache key.
        if (!_cache.TryGetValue(key, out cacheEntry))
        {
            // Key not in cache, so get data.
            cacheEntry = o;

            // Set cache options.
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                // Keep in cache for this time, reset time if accessed.
                .SetSlidingExpiration(TimeSpan.FromSeconds(7200));

            // Save data in cache.
            _cache.Set(key, cacheEntry, cacheEntryOptions);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.