aspnet/Caching

Why should I use services.AddMemoryCache(); instead of services.AddDistributedMemoryCache();

Closed this issue · 2 comments

I wonder why we may want to use In-Memory cache where we can use plain AddDistributedMemoryCache (no sql, no redis)?

I know the difference between MemoryCache and DistributedCache, the only part that I don't understand is if I can have same features IMemoryCache through IDistributedCache one, I can decorate my classes with IDistributedCache and it will be good for change, scale etc. Well, do I need those? maybe or maybe not, but my gut says there should be something fundamentally different between those two.

Please advise.

Eilon commented

The two cache systems are quite different:

  1. IMemoryCache is for storing live object graphs, e.g. a List<Customer>, or a ComplexCrazyObjectGraph
  2. IDistributedGraph is for storing serialized bytes, i.e. byte[]. If you want to store a List<Customer> in there, it must first be serialized. But, not all data types are serializable, so that is a limitation of this interface. But, this interface can be used with distributed cache stores, such as SQL Server, Redis, or other implementations.