I am trying to write a class to handle Memory cache in a .net core class library. If I use not the core then I could write
using System.Runtime.Caching;
using S
If you using Asp.net core you no need to custom SingleTon for cache, because Asp.net core is supported DI for your Cache class.
To using IMemoryCache
to set data to the memory of the server you can do as below:
public void Add(T o, string key)
{
if (IsEnableCache)
{
T cacheEntry;
// Look for cache key.
if (!_cache.TryGetValue(key, out cacheEntry))
{
// Key not in cache, so get data.
cacheEntry = o;
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromSeconds(7200));
// Save data in cache.
_cache.Set(key, cacheEntry, cacheEntryOptions);
}
}
}
For more detail, you can read the article implement in-memory in asp.net core