Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dotnet System.Web.Caching.Cache vs System.Runtime.Caching.MemoryCache

I've got a class that needs to store data in a cache. Originally I used it in an asp.net application so I used System.Web.Caching.Cache.

Now I need to use it in a Windows Service. Now, as I understand it, I should not use the asp.net cache in a not asp.net application, so I was looking into MemoryCache.

The problem is that they are not compatible, so either I change to use MemoryCache in the asp.net application, or I will need to create an adapter so ensure that the two cache implementations have the same interface (maybe derive from ObjectCache and use the asp.net cache internally?)

What are the implications of using MemoryCache in an asp.net?

Nadav

like image 369
Nadav Avatar asked Oct 07 '10 14:10

Nadav


People also ask

What are the different caching techniques available in .NET Core?

ASP.NET Core supports two types of caching out of the box: In-Memory Caching – This stores data on the application server memory. Distributed Caching – This stores data on an external service that multiple application servers can share.

What is runtime cache?

Runtime caching refers to gradually adding responses to a cache "as you go". While runtime caching doesn't help with the reliability of the current request, it can help make future requests for the same URL more reliable.

Is MemoryCache a singleton?

Note that the MemoryCache is a singleton, but within the process. It is not (yet) a DistributedCache. Also note that Caching is Complex(tm) and that thousands of pages have been written about caching by smart people.

What is MemoryCache C#?

In-Memory Cache is used for when you want to implement cache in a single process. When the process dies, the cache dies with it. If you're running the same process on several servers, you will have a separate cache for each server. Persistent in-process Cache is when you back up your cache outside of process memory.


1 Answers

I would go with your second option and refactor things a little bit. I would create an Interface and two Providers (which are your adapters):

public interface ICachingProvider
{
    void AddItem(string key, object value);
    object GetItem(string key);
}

public AspNetCacheProvider : ICachingProvider
{
    // Adapt System.web.Caching.Cache to match Interface
}

public MemoryCacheProvider : ICachingProvider
{
    // Adapt System.Runtime.Caching.MemoryCache to match Interface
}
like image 156
Justin Niessner Avatar answered Sep 21 '22 13:09

Justin Niessner