Beispiel #1
0
        /// <summary>
        /// Register a cache item for remote clear/refresh access via controller
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="getterExpression"></param>
        /// <param name="doInitialize"></param>
        public void RegisterCacheItem <TItem>(Expression <Func <TItem> > getterExpression, bool doInitialize)
            where TItem : class
        {
            if (getterExpression == null)
            {
                throw new CacheException("Cache item not registered - received undefined getterExpression");
            }

            MethodInfo method;

            object[] arguments;
            LambdaHelper.GetMethodInfoAndArguments(getterExpression, out method, out arguments);

            // CacheListAttribute is intentionally not supported, as cacheItemKey vary according to input
            // these should be dealt with by using a dedicated cache and clearing this entire dedicated cache
            var cacheName = method.GetCustomAttributesData()
                            .Where(a =>
                                   a.AttributeType.FullName == "PubComp.Caching.AopCaching.CacheAttribute" &&
                                   a.ConstructorArguments.Any() &&
                                   a.ConstructorArguments.First().ArgumentType == typeof(string))
                            .Select(a => (a.ConstructorArguments.First().Value ?? string.Empty).ToString())
                            .FirstOrDefault();

            var methodType = method.DeclaringType;

            if (methodType == null)
            {
                throw new CacheException("Cache item not registered - invalid getterExpression");
            }

            if (cacheName == null)
            {
                cacheName = methodType.FullName;
            }

            if (string.IsNullOrEmpty(cacheName))
            {
                throw new CacheException("Cache item not registered - received undefined cacheName");
            }

            var itemKey = CacheKey.GetKey(getterExpression);

            if (string.IsNullOrEmpty(itemKey))
            {
                throw new CacheException("Cache item not registered - received undefined itemKey");
            }

            RegisteredCacheNames.GetOrAdd(cacheName, false);

            var getter = getterExpression.Compile();

            Func <Tuple <string, string>, Func <object>, Func <object> > updateGetter
                = (k, o) => getter;

            RegisteredCacheItems.AddOrUpdate(
                Tuple.Create(cacheName, itemKey), getter, updateGetter);

            if (doInitialize)
            {
                if (!TrySetCacheItem(cacheName, itemKey, getter))
                {
                    throw new CacheException("Cache item not initialized - cache not defined: " + cacheName);
                }
            }
        }