How to use Microsoft.Extensions.Caching.Memory for object caching in .net core
See original GitHub issueI were system.runtime.caching for object caching. i have heard that it is recommended to use Microsoft.Extensions.Caching.Memory for caching in .net core 3.1
I am not able to create object of memorycache . My logic for Caching in System.Runtime caching is as following . Please help me implementing similar object caching with Microsoft.Extensions.Caching.Memory
public static class MemoryCacheManager
{
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static bool EnableCache = false;
public static void Add<T>(string key, T o)
{
try
{
if (o != null)//https://github.com/mikeedwards83/Glass.Mapper/issues/283
{
if (CacheEnable())
{
if (!Exists(key))
{
ObjectCache defCache = MemoryCache.Default;
defCache.Add(key, o, new CacheItemPolicy { Priority = CacheItemPriority.Default });
Logger.DebugFormat("Key : {0} inserted", key);
}
}
}
}
catch (Exception ex)
{
Logger.Fatal($"key:{key},exception:{ex.Message}");
}
}
private static bool CacheEnable()
{
return EnableCache;
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static bool Clear(string key)
{
var keyDeleted = false;
if (CacheEnable())
{
try
{
if (Exists(key))
{
ObjectCache defCache = MemoryCache.Default;
defCache.Remove(key);
Logger.InfoFormat("Key : {0} cleared", key);
keyDeleted = true;
}
else
Logger.InfoFormat("key : {0} not found", key);
}
catch (Exception ex)
{
Logger.Fatal($"key:{key},exception:{ex.Message}");
}
}
return keyDeleted;
}
public static bool Exists(string key)
{
ObjectCache defCache = MemoryCache.Default;
return defCache[key] != null;
}
public static T Get<T>(string key)
{
try
{
if (CacheEnable())
{
if (Exists(key))
{
ObjectCache defCache = MemoryCache.Default;
return (T)defCache[key];
}
Logger.DebugFormat("Key : {0} does not exists", key);
}
return default;
}
catch (Exception ex)
{
Logger.Fatal($"key:{key},exception:{ex.Message}");
return default;
}
}
public static bool ClearFromTablePrefix(string key)
{
var keyDeleted = false;
if (CacheEnable())
{
var cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
var cacheItem = new List<string>();
foreach (var cacheKey in cacheKeys)
{
if (cacheKey.StartsWith(key))
cacheItem.Add(cacheKey);
}
Logger.DebugFormat("Number of Key(s) found {0}, with Prefix {1}", cacheItem.Count, key);
try
{
foreach (var newkey in cacheItem)
{
ObjectCache defCache = MemoryCache.Default;
defCache.Remove(key);
//if (LogCacheRelatedActivities)
{
Logger.DebugFormat("Key : {0} cleared", newkey);
}
}
keyDeleted = true;
}
catch (Exception ex)
{
Logger.Fatal($"key:{key},exception:{ex.Message}");
}
}
return keyDeleted;
}
public static bool RemoveAllCache()
{
try
{
if (CacheEnable())
{
var cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
foreach (var cacheKey in cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
}
return true;
}
catch (Exception ex)
{
Logger.Fatal(ex.Message);
return false;
}
}
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Caching in .NET
In this section, you'll learn about the Microsoft.Extensions.Caching.Memory package. The current implementation of the IMemoryCache is a wrapper ...
Read more >Simple In-Memory Caching in .Net Core with IMemoryCache
Caching is the process of storing the data that's frequently used so that data can be served faster for any future requests. UPDATE...
Read more >How to use MemoryCache in C# Core Console app?
Here is the complete console application code in .NET Core using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.
Read more >In Memory Caching on .NET 6.0 - Nishān Wickramarathna
Today we're going to see how to do application data caching using Microsoft.Extensions.Caching.Memory/ IMemoryCache. Caching can significantly improve the ...
Read more >In-Memory Caching in ASP.NET Core
A good caching strategy is to use a combination of sliding and absolute expiration. Priority – This sets the priority of the cached...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Take a look at the docs for a good starting point. This repo doesn’t exist to implement things for you, but if you run into specific problems that you don’t know how to solve, we might be able to provide pointers to them.
Glad to hear it!