IMemoryCache-单例或依赖注入

时间:2020-01-24 06:54:25

标签: c# asp.net asp.net-mvc


public class CacheController
{
    public IMemoryCache _memoryCache {get; set;}

    public string getCacheMethodOne(string token)
    {
        string cacheValue = null;
        string cacheKey = null;

        if (!_memoryCache.TryGetValue<string>("123456", out cacheValue))
        {
            cacheValue = token;
            cacheKey = "123456";

            var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(2));

            _memoryCache.Set<string>("123456", cacheValue, cacheEntryOptions);
        }
        return cacheKey;
    }

}


以下代码行存在问题: string otp = new CacheController().getCacheMethodOne(ClientJsonOtp.ToString()); 引发异常。

对象引用未设置为对象的实例。

我应该创建IMemorycahce的新实例。 如果我这样做,会影响缓存。因为它可能会丢失先前的缓存实例。

try
{
    var finalResult = result.Content.ReadAsStringAsync().Result;
    var ClientJsonOtp = JsonConvert.DeserializeObject(finalResult);
    string otp = new CacheController().getCacheMethodOne(ClientJsonOtp.ToString());
    return Json(ClientJsonOtp, JsonRequestBehavior.AllowGet);
}


1 个答案:

答案 0 :(得分:1)

您需要创建一个,至少一次。否则,它将始终为null。

您可以在调用空构造函数时这样做:

public CacheController()
    {
        this._memoryCache = new // whatever memory cache you choose;
    }

您甚至可以使用依赖项注入将其更好地注入到某个地方。地点取决于应用程序类型。

但是最重要的是,尝试只缓存一次。每次创建一个时,都会丢失前一个,因此,您将尝试使用单例模式,或者使用单实例配置进行注入,然后由DI容器处理其余部分。

单例实现的示例:here

您可以使用以下方式访问:

Cache.Instance.Read(//what)

这是缓存实现

using System;
using System.Configuration;
using System.Runtime.Caching;

namespace Client.Project.HelperClasses
{

    /// <summary>
    /// Thread Safe Singleton Cache Class
    /// </summary>
    public sealed class Cache
    {
        private static volatile Cache instance; //  Locks var until assignment is complete for double safety
        private static MemoryCache memoryCache;
        private static object syncRoot = new Object();
        private static string settingMemoryCacheName;
        private static double settingCacheExpirationTimeInMinutes;
        private Cache() { }

        /// <summary>
        /// Singleton Cache Instance
        /// </summary>
        public static Cache Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            InitializeInstance();

                        }
                    }
                }
                return instance;
            }
        }

        private static void InitializeInstance()
        {
            var appSettings = ConfigurationManager.AppSettings;
            settingMemoryCacheName = appSettings["MemoryCacheName"];
            if (settingMemoryCacheName == null)
                throw new Exception("Please enter a name for the cache in app.config, under 'MemoryCacheName'");

            if (! Double.TryParse(appSettings["CacheExpirationTimeInMinutes"], out settingCacheExpirationTimeInMinutes))
                throw new Exception("Please enter how many minutes the cache should be kept in app.config, under 'CacheExpirationTimeInMinutes'");

            instance = new Cache();
            memoryCache = new MemoryCache(settingMemoryCacheName);
        }

        /// <summary>
        /// Writes Key Value Pair to Cache
        /// </summary>
        /// <param name="Key">Key to associate Value with in Cache</param>
        /// <param name="Value">Value to be stored in Cache associated with Key</param>
        public void Write(string Key, object Value)
        {
            memoryCache.Add(Key, Value, DateTimeOffset.Now.AddMinutes(settingCacheExpirationTimeInMinutes));
        }

        /// <summary>
        /// Returns Value stored in Cache
        /// </summary>
        /// <param name="Key"></param>
        /// <returns>Value stored in cache</returns>
        public object Read(string Key)
        {
            return memoryCache.Get(Key);
        }

        /// <summary>
        /// Returns Value stored in Cache, null if non existent
        /// </summary>
        /// <param name="Key"></param>
        /// <returns>Value stored in cache</returns>
        public object TryRead(string Key)
        {
            try
            {
                return memoryCache.Get(Key);
            }
            catch (Exception)
            {
                return null;
            }

        }

    }

}