依頼によりキャッシュ操作をより優雅に

5778 ワード

string key = sysVar.CacheKey.CurrentUser;
var CurrentUser = _cacheManager.Get(key, ()=>{ ctx.GetCurrentUser();});
キャッシュ操作インタフェースの拡張方法:
    public static class CacheExtensions

    {

        /// <summary>

        ///  key , 

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="cacheManager"></param>

        /// <param name="key"></param>

        /// <param name="acquire"></param>

        /// <returns></returns>

        public static T Get<T>(this ICacheManager cacheManager, string key, Func<T> acquire)

        {

            return Get(cacheManager, key, 60, acquire);

        }



        /// <summary>

        ///  key, ( )。

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="cacheManager"></param>

        /// <param name="key"></param>

        /// <param name="cacheTime"> </param>

        /// <param name="acquire"></param>

        /// <returns></returns>

        public static T Get<T>(this ICacheManager cacheManager, string key, int cacheTime, Func<T> acquire)

        {

            if (cacheManager.IsSet(key)) // 

            {

                return cacheManager.Get<T>(key); // 

            }

            else

            {

                var result = acquire(); //  //if (result != null)

                cacheManager.Set(key, result, cacheTime); //  return result;          // 

            }

        }

    }

 _cacheManager.Get(key, () => { ......; return result; }
    public interface ICacheManager

    {

        T Get<T>(string key);

        void Set(string key, object data, int cacheTime);



        /// <summary>

        ///  

        /// </summary>

        bool IsSet(string key);

        void Remove(string key);

        void RemoveByPattern(string pattern);

        void Clear();

    }