コード例 #1
0
ファイル: MethodHandler.cs プロジェクト: StianLohna/AutoBox
        /// <summary>
        /// Resolves the handler for the specific config item.
        /// </summary>
        public static IHandler Resolve(MethodInfo methodInfo, object[] arguments)
        {
            var configuration = (Configuration)ServiceLocator.Current.GetInstance<IConfiguration>();

            var methodConfig = ServiceLocator.Current.GetInstance<IMethodContainer>();

            IMethod metaData = methodConfig.Get(methodInfo, arguments);

            var configItem = configuration.GetConfigItem(metaData);

            IHandler handler = new BaseMethodHandler();

            if (configItem != null)
            {
                if (configItem.CacheDuration.TotalMilliseconds > 0)
                {
                    string containerId =  (ServiceLocator.Current as Locator.AutoBoxServiceLocator).TypeContainer.Id;
                    string compositeKey = string.Format("{0}+{1}", metaData.Key, containerId);

                    handler =   new CacheMethodHandler(compositeKey, configItem.CacheDuration, configItem.InValidated, arguments);

                    if (configItem.InValidated) configItem.InValidated = false;
                }
                // has items to invalidate.
                configItem.InvalidateDependencies();
            }

            return handler;
        }
コード例 #2
0
        /// <summary>
        /// Returns the cached object. When new it the first stores then returns the cached item.
        /// </summary>
        /// <param name="target">Target object</param>
        /// <param name="invocation">Target invocation</param>
        public object Invoke(object target, IMethodInvocation invocation)
        {
            var provider = CacheProviderFactory.Create();

            string cacheKey = this.GetUniqueKey();

            object result = invalidated ? null : provider.GetObject(cacheKey);

            JsonSerializer serializer = new JsonSerializer()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            if (result == null)
            {
                result = new BaseMethodHandler().Invoke(target, invocation);

                var builder = new StringBuilder();

                using (var writer = new StringWriter(builder))
                {
                    serializer.Serialize(new JsonTextWriter(writer), result);
                }

                string content = builder.ToString();

                provider.SetObject(cacheKey, content, DateTime.Now.AddMilliseconds(cacheDuration.TotalMilliseconds));

                return result;
            }

            using (var reader = new StringReader((string)result))
            {
                result = serializer.Deserialize(new JsonTextReader(reader), invocation.Method.ReturnType);
            }

            return result;
        }