Register the dependency in Main
:
builder.Services.AddMemoryCache();
Inject the service into your class constructor:
public class MyClass(IMemoryCache memoryCache) { ... }
Set a cache value:
memoryCache.Set("cacheKeyName", myType, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5), // Expire if the cache item has been inactive for 5 minutes
});
Retrieve a cached value:
var cached = memoryCache.TryGetValue<MyType>("cacheKeyName", out var myType);