0

I'm using Microsoft.Extensions.Caching.Memory, as I hav read it is the newer implementation of System.Runtime.Caching.

I have been reading that it's not recommended to have more than one instances of MemoryCache along the application to take advantage of the memory management.

I need to store more than one type of elements in the Cache. Currently I'm using tuples as keys to locate items in cache. But maybe I need to use it on more classes.

I can do it using my IoC like Autofac to include it as a Singleton and maybe doing some interface to encapsulate the cache management.

I can use tuples to store key type and key, or avoid using tuples and creating a class to represent different type of keys implementing IEquatable.

public void AddItem(object key, object value){
    _memoryCache.Add((keyType: key.GetType().FullName, keyValue: key), value);
}

What is the best solution to store different type of items and get them also? It's true that it's not recommended to have more than one instance of MemoryCache? I'm searching for a good solution in terms of performance to get items as fast as possible.

3
  • 1
    MemoryCache is a wrapper around ConcurrentDictionary. I see no reason to limit ourselves to only one instance. That's ridiculous. Commented Jun 20, 2023 at 4:58
  • @freakish I have read in other posts that it was not recommended to have more instances. Example: stackoverflow.com/questions/8463962/… Commented Jun 20, 2023 at 21:31
  • Honestly, this highly voted answer can be summed up as: multiple cache instances come with a minor memory overhead (obviously). As long as you remember that it is completely fine. And you can also read in the linked question that many, many people do that. Commented Jun 21, 2023 at 5:21

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.