How to use MemoryCache in C# Core Console app?
After configuring the provider retrieve the cache via the GetService
extension method
var provider = new ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();
//And now?
var cache = provider.GetService<IMemoryCache>();
//...other code removed for brevity;
From comments:
It's not needed to use dependency injection, the only thing needed was disposing the return value of CreateEntry(). The entry returned by
CreateEntry
needs to be disposed. On dispose, it is added to the cache:
using (var entry = cache.CreateEntry("item2")) {
entry.Value = 2;
entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1);
}
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object result = cache.Set("Key", new object());
bool found = cache.TryGetValue("Key", out result);
See full Memory Cache Sample in GitHub.
You need to add NuGet Microsoft.Extensions.Caching.Memory packages in your project for use MemoryCache
Here is the complete console application code in .NET Core
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using System;
using System.Threading;
namespace InMemoryNetCore
{
class Program
{
static void Main(string[] args)
{
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object result;
string key = "KeyName";
// Create / Overwrite
result = cache.Set(key, "Testing 1");
result = cache.Set(key, "Update 1");
// Retrieve, null if not found
result = cache.Get(key);
Console.WriteLine("Output of KeyName Value="+result);
// Check if Exists
bool found = cache.TryGetValue(key, out result);
Console.WriteLine("KeyName Found=" + result);
// Delete item
cache.Remove(key);
//set item with token expiration and callback
TimeSpan expirationMinutes = System.TimeSpan.FromSeconds(0.1);
var expirationTime = DateTime.Now.Add(expirationMinutes);
var expirationToken = new CancellationChangeToken(
new CancellationTokenSource(TimeSpan.FromMinutes(0.001)).Token);
// Create cache item which executes call back function
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Pin to cache.
.SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.Normal)
// Set the actual expiration time
.SetAbsoluteExpiration(expirationTime)
// Force eviction to run
.AddExpirationToken(expirationToken)
// Add eviction callback
.RegisterPostEvictionCallback(callback: CacheItemRemoved);
//add cache Item with options of callback
result = cache.Set(key,"Call back cache Item", cacheEntryOptions);
Console.WriteLine(result);
Console.ReadKey();
}
private static void CacheItemRemoved(object key, object value, EvictionReason reason, object state)
{
Console.WriteLine(key + " " + value + " removed from cache due to:" + reason);
}
}
}
Source : In Memory cache C# (Explanation with example in .NET and .NET Core)