question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use Microsoft.Extensions.Caching.Memory for object caching in .net core

See original GitHub issue

I 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:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
Pilchiecommented, May 5, 2020

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.

0reactions
Pilchiecommented, May 6, 2020

Glad to hear it!

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found