In .NET, why is ObjectCache the preferred type over MemoryCache?

860 Views Asked by At

So many examples of using the memory cache in .NET (including the official docs) instantiate it with:

private readonly ObjectCache memoryCache = MemoryCache.Default;

Is there any reason to prefer this over:

private readonly MemoryCache memoryCache = MemoryCache.Default;
3

There are 3 best solutions below

3
On BEST ANSWER

The reason to prefer ObjectCache over MemoryCache is the L in SOLID...

Liskov substitution principle:

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

ObjectCache is replaceable by any of its subtypes including MemoryCache while MemoryCache is not replaceable by anything forcing you into a specific implementation.

0
On

It's similar to declaring a variable or receiving a parameter of type Stream rather than FileStream or MemoryStream: the flexibility of not having to care which implementation you have.

ObjectCache is the base class of MemoryCache. At instantiation, you're creating a specific implementation, but elsewhere in your code, it shouldn't matter which implementation you have. What matters is the common interface provided by the base class. You can change the instantiation to create a different type and the code that uses the cache doesn't have to be modified.

0
On

ObjectCache is a abstract class so you cant directly instantiate it and demonstrates how you should build a Cache that adheres to the rules the person who wrote ObjectCache wants you to obey.

So that MemoryCache inherits from ObjectCache. For everyday use you would use MemoryCashe. But if you want to your own you could inherit from objectCashe and write your own methods.

public class MemoryCache : ObjectCache, 
IEnumerable, IDisposable