创建microsoft.extensions.caching.memory作为单顿类

发布于 2025-01-22 12:06:36 字数 2810 浏览 0 评论 0原文

Im trying to use Microsoft.Extensions.Caching.Memory as singleton class in Asp.net MVC 5.

Problem is with each call the Instance Variable returns null and class reinstantiating it

self.(old value of Cache will删除)

这是我的缓存类:

public class CacheManagerHelper<TItem>
    {

  private static CacheManagerHelper<TItem> instance;
        private static MemoryCache memoryCache;
        private static object syncRoot = new();
        private CacheManagerHelper() { }


        public static CacheManagerHelper<TItem> Instance
        {
            get
            {
                        if (instance == null)
                        {

                            instance = new CacheManagerHelper<TItem>();
                            memoryCache = new MemoryCache(new MemoryCacheOptions()
                            {
                            });
                        }

                return instance;
            }
        }


        
        private static ConcurrentDictionary<object, SemaphoreSlim> _locks = new ConcurrentDictionary<object, SemaphoreSlim>();

        public async Task<TItem> GetOrCreate(object key, Func<Task<TItem>> createItem)
        {
            TItem cacheEntry;

            if (!memoryCache.TryGetValue(key, out cacheEntry))
            {
                SemaphoreSlim mylock = _locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

                await mylock.WaitAsync();
                try
                {
                    if (!memoryCache.TryGetValue(key, out cacheEntry))
                    {
                        cacheEntry = await createItem();
                        var cacheEntryOptions = new MemoryCacheEntryOptions()
                   .SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.NeverRemove)
                   .SetSlidingExpiration(TimeSpan.FromHours(24))
                   .SetAbsoluteExpiration(TimeSpan.FromHours(48));


                        memoryCache.Set(key, cacheEntry);
                    }
                }
                finally
                {
                    mylock.Release();
                }
            }
            return cacheEntry;
        }

        public T Get<T>(string key)
        {
            return (T)Convert.ChangeType(memoryCache.Get(key), typeof(T));
        }

        public void RemoveCache(string key)
        {
            memoryCache.Remove(key);
        }

        public static void ClearAllCacheObject()
        {
            IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();

            while (enumerator.MoveNext())
                HttpContext.Current.Cache.Remove(enumerator.Key.ToString());

        }
}

Im trying to use Microsoft.Extensions.Caching.Memory as singleton class in Asp.net MVC 5.

Problem is with each call the Instance Variable returns null and class reinstantiating it

self.(old value of Cache will be deleted)

this is my cache class :

public class CacheManagerHelper<TItem>
    {

  private static CacheManagerHelper<TItem> instance;
        private static MemoryCache memoryCache;
        private static object syncRoot = new();
        private CacheManagerHelper() { }


        public static CacheManagerHelper<TItem> Instance
        {
            get
            {
                        if (instance == null)
                        {

                            instance = new CacheManagerHelper<TItem>();
                            memoryCache = new MemoryCache(new MemoryCacheOptions()
                            {
                            });
                        }

                return instance;
            }
        }


        
        private static ConcurrentDictionary<object, SemaphoreSlim> _locks = new ConcurrentDictionary<object, SemaphoreSlim>();

        public async Task<TItem> GetOrCreate(object key, Func<Task<TItem>> createItem)
        {
            TItem cacheEntry;

            if (!memoryCache.TryGetValue(key, out cacheEntry))
            {
                SemaphoreSlim mylock = _locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

                await mylock.WaitAsync();
                try
                {
                    if (!memoryCache.TryGetValue(key, out cacheEntry))
                    {
                        cacheEntry = await createItem();
                        var cacheEntryOptions = new MemoryCacheEntryOptions()
                   .SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.NeverRemove)
                   .SetSlidingExpiration(TimeSpan.FromHours(24))
                   .SetAbsoluteExpiration(TimeSpan.FromHours(48));


                        memoryCache.Set(key, cacheEntry);
                    }
                }
                finally
                {
                    mylock.Release();
                }
            }
            return cacheEntry;
        }

        public T Get<T>(string key)
        {
            return (T)Convert.ChangeType(memoryCache.Get(key), typeof(T));
        }

        public void RemoveCache(string key)
        {
            memoryCache.Remove(key);
        }

        public static void ClearAllCacheObject()
        {
            IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();

            while (enumerator.MoveNext())
                HttpContext.Current.Cache.Remove(enumerator.Key.ToString());

        }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文