How to cache data in a MVC application

后端 未结 14 1165
鱼传尺愫
鱼传尺愫 2020-11-22 11:39

I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

In my scena

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:11

    I use two classes. First one the cache core object:

    public class Cacher
        where TValue : class
    {
        #region Properties
        private Func _init;
        public string Key { get; private set; }
        public TValue Value
        {
            get
            {
                var item = HttpRuntime.Cache.Get(Key) as TValue;
                if (item == null)
                {
                    item = _init();
                    HttpContext.Current.Cache.Insert(Key, item);
                }
                return item;
            }
        }
        #endregion
    
        #region Constructor
        public Cacher(string key, Func init)
        {
            Key = key;
            _init = init;
        }
        #endregion
    
        #region Methods
        public void Refresh()
        {
            HttpRuntime.Cache.Remove(Key);
        }
        #endregion
    }
    

    Second one is list of cache objects:

    public static class Caches
    {
        static Caches()
        {
            Languages = new Cacher>("Languages", () =>
                                                              {
                                                                  using (var context = new WordsContext())
                                                                  {
                                                                      return context.Languages.ToList();
                                                                  }
                                                              });
        }
        public static Cacher> Languages { get; private set; }
    }
    

提交回复
热议问题