Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryCache.Default not available in .NET Core?

I'm porting some code from .NET 4.6 til .NET Core and have run into some problems with MemoryCache. The 4.6 code is using MemoryCache.Default to instantiate the cache, but this doesn't seem to be available in .NET Core. Is there any equivalent to this in .NET Core or should I rather new up my own MemoryCache as a singleton and inject it via IOC?

like image 472
henningst Avatar asked Nov 20 '15 08:11

henningst


People also ask

How do I use MemoryCache in .NET Core?

Implementing an In-Memory Cache Let's start by creating an ASP.NET Core Web API using the ASP.NET Core Web API with EF Core Code-First Approach. First, we inject the IMemoryCache and ILogger into the EmployeeController . Then, in the listing action method, we check if the employeeList data is available in the cache.

Is .NET Core MemoryCache thread safe?

NET Framework is thread-safe (according to the documentation).

How do I reset my MemoryCache?

When you turn off your PC, all the data held in your system memory is wiped. That means that the quickest route to clearing your Windows memory cache is to just turn your PC off. Restart it or switch it off and boot it up again manually —either way, the brief interruption in power will erase the data held within.


1 Answers

System.Runtime.Caching.MemoryCache and Microsoft.Extensions.Caching.Memory.MemoryCache are completely different implementations.

They are similar but have different sets of issues/caveats.

The System.Runtime.Caching.MemoryCache is the older version (4.6) and is based on ObjectCache and is typically used via MemoryCache.Default as you described. It actually can be used in .Net Core via the NuGet library in .Net standard format. https://www.nuget.org/packages/System.Runtime.Caching/

The Microsoft.Extensions.Caching.Memory.MemoryCache is the new .NET core version and is generally used in newer ASP core applications. It implements IMemoryCache and is typically added in the services as described above by @Bogdan

https://github.com/aspnet/Extensions/blob/master/src/Caching/Memory/src/MemoryCache.cs https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/

like image 93
Menace Avatar answered Sep 27 '22 20:09

Menace