Esempio n. 1
0
        /// <summary>
        /// 按服务名称,随机返回一个服务地址
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="minute"></param>
        /// <returns></returns>
        public ServiceInfo GetServiceInfo(string serviceName, double minute = 0)
        {
            Dictionary <string, ServiceInfo> all;

            if (minute > 0)
            {
                all = DelegateCache.Init("consulServiceCache", minute, () =>
                {
                    return(GetAllServices());
                });
            }
            else
            {
                all = GetAllServices();
            }
            var services = all.Values.Where(b => b.Service == serviceName).ToList();

            if (services.Count == 0)
            {
                throw new Exception($"找不到可用的服务:{serviceName}");
            }
            int k = rng.Next(services.Count);

            return(services[k]);
        }
Esempio n. 2
0
        public TDest To <TDest>(TDest destination, string keyMemberName = null, string flatteningToken = null, bool clearCollections = false)
        {
            if (destination != null)
            {
                Action <TSource, TDest> compiledAction = GetCachedActionOverDestination <TDest>(keyMemberName, clearCollections, flatteningToken);

                if (compiledAction == null)
                {
                    Expression <Action <TSource, TDest> > queryExpression = GetCachedExpressionOverDestination <TDest>(keyMemberName, clearCollections, flatteningToken) ?? BuildExpressionOverDestination <TDest>(clearCollections, keyMemberName, flatteningToken);

                    compiledAction = queryExpression.Compile();

                    string key = GetCacheKey <Action <TSource, TDest> >(flatteningToken, keyMemberName, clearCollections);

                    DelegateCache.TryAdd(key, compiledAction);
                }

                compiledAction.Invoke(source, destination);
            }
            else
            {
                return(this.To <TDest>(flatteningToken));
            }

            return(destination);
        }
Esempio n. 3
0
        public void ActionTest()
        {
            DelegateCache cache = new DelegateCache();

            int val = -1;

            DelegateCache.CachedAction action = delegate()
            {
                ++val;
            };

            cache.SaveAction(action, TimeSpan.FromSeconds(3));

            for (int i = 0; i < 4; i++)
            {
                cache.InvokeAction(action);

                if (i < 3)
                {
                    Assert.AreEqual(val, 0);
                }
                else
                {
                    Assert.AreEqual(val, 1);
                }

                Thread.Sleep(1100);
            }
        }
Esempio n. 4
0
        public void FuncTest()
        {
            DelegateCache cache = new DelegateCache();

            int val = 0;

            DelegateCache.CachedFunc <int> func = delegate()
            {
                return(val++);
            };

            cache.SaveFunc(func, TimeSpan.FromSeconds(5));

            for (int i = 0; i < 6; i++)
            {
                int v = cache.InvokeFunc(func);

                if (i < 5)
                {
                    Assert.AreEqual(v, 0);
                }
                else
                {
                    Assert.AreEqual(v, 1);
                }

                Thread.Sleep(1100);
            }
        }
 /// <summary>
 /// Creates a new instance of <see cref="WampIncomingMessageHandler{TMessage,TClient}"/>
 /// given <paramref name="wampRequestMapper"/> and
 /// <paramref name="methodBuilder"/>
 /// </summary>
 /// <param name="wampRequestMapper">The <see cref="IWampRequestMapper{TRequest}"/>
 /// used in order to map <see cref="WampMessage{TMessage}"/>s to their suitable methods.</param>
 /// <param name="methodBuilder">The <see cref="IMethodBuilder{TKey,TMethod}"/> used
 /// in order to build the corresponding methods.</param>
 public WampIncomingMessageHandler
     (IWampRequestMapper <TMessage> wampRequestMapper,
     IMethodBuilder <WampMethodInfo, Action <TClient, WampMessage <TMessage> > > methodBuilder)
 {
     mWampRequestMapper = wampRequestMapper;
     mLogger            = LogProvider.GetLogger(this.GetType());
     mDelegateCache     = new DelegateCache <WampMethodInfo, Action <TClient, WampMessage <TMessage> > >(methodBuilder);
 }
    protected void OnClick()
    {
        ClickHandler ch = (ClickHandler)DelegateCache.Fetch(this, clickEventKey);

        if (ch != null)
        {
            ch(this, null);
        }
    }
Esempio n. 7
0
        private object GetMapMethod(TypePair key, Func <CompiledDelegate, object> propertyAccessor)
        {
            CompiledDelegate @delegate = null;

            DelegateCache.TryGetValue(key, out @delegate);
            var mapMethod = propertyAccessor(@delegate);

            return(mapMethod);
        }
Esempio n. 8
0
        /// <summary>
        /// Locate specific type using extra data or key
        /// </summary>
        /// <param name="type">type to locate</param>
        /// <param name="extraData">extra data to be used during construction</param>
        /// <param name="consider"></param>
        /// <param name="withKey">key to use for locating type</param>
        /// <param name="isDynamic"></param>
        /// <returns>located instance</returns>
        // ReSharper disable once MethodOverloadWithOptionalParameter
        public override object Locate(Type type, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
        {
            if (isDynamic || withKey != null || consider != null)
            {
                return(LocateFromParent(type, extraData, consider, withKey, false, isDynamic));
            }

            return(DelegateCache.ExecuteActivationStrategyDelegateWithContext(type, this, false, extraData != null ? CreateContext(extraData) : null));
        }
Esempio n. 9
0
 private ResolutionScope(IResolverSelector resolverSelector,
                         IExpressionBuilder expressionBuilder, IContainerContext containerContext,
                         DelegateCache delegateCache, object name)
 {
     this.resolverSelector  = resolverSelector;
     this.expressionBuilder = expressionBuilder;
     this.containerContext  = containerContext;
     this.Name          = name;
     this.delegateCache = delegateCache;
 }
Esempio n. 10
0
 /// <summary>
 /// Converts the <see cref="DbDataReader"/> into an enumerable of <see cref="ExpandoObject"/> object.
 /// </summary>
 /// <param name="reader">The <see cref="DbDataReader"/> to be converted.</param>
 /// <param name="basedOnFields">Check whether to create a delegate based on the data reader fields.</param>
 /// <returns>An array of <see cref="ExpandoObject"/> objects.</returns>
 internal static IEnumerable <dynamic> ToEnumerable(DbDataReader reader, bool basedOnFields = false)
 {
     if (reader != null && reader.HasRows)
     {
         var @delegate = DelegateCache.GetDataReaderToExpandoObjectDelegate(reader, basedOnFields);
         while (reader.Read())
         {
             yield return(@delegate(reader));
         }
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Returns an empty <see cref="IEnumerable{T}"/> that has the specified type argument.
        /// </summary>
        /// <param name="type">
        /// The <see cref="Type"/> to assign to the type parameter of the returned
        /// generic <see cref="IEnumerable{T}"/>.
        /// </param>
        /// <returns>
        /// The <see cref="object"/> representing the empty enumerable.
        /// </returns>
        public static object Empty(Type type)
        {
            MethodBaseCacheItem key = GetMethodCacheKey(type);

            if (!DelegateCache.TryGetValue(key, out var f))
            {
                f = StaticMethod <object>(EmptyMethod.MakeGenericMethod(type));
                DelegateCache[key] = f;
            }

            return(((Func <object, object>)f)(type));
        }
Esempio n. 12
0
        /// <summary>
        /// Casts the elements of the given <see cref="IEnumerable"/> to the specified type.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> to cast to.</param>
        /// <param name="value">
        /// The <see cref="IEnumerable"/> to cast the items of.
        /// </param>
        /// <returns>
        /// The <see cref="object"/> representing the cast enumerable.
        /// </returns>
        public static object Cast(Type type, IEnumerable value)
        {
            MethodBaseCacheItem key = GetMethodCacheKey(type);

            if (!DelegateCache.TryGetValue(key, out var f))
            {
                f = StaticMethodSingleParameter <object>(CastMethod.MakeGenericMethod(type));
                DelegateCache[key] = f;
            }

            return(((Func <object, object>)f)(value));
        }
Esempio n. 13
0
        private ResolutionScope(ExpressionFactory expressionBuilder, IContainerContext containerContext,
                                DelegateCacheProvider delegateCacheProvider, object name)
        {
            this.expressionFactory = expressionBuilder;
            this.containerContext  = containerContext;
            this.Name = name;
            this.delegateCacheProvider = delegateCacheProvider;

            this.delegateCache = name == null
                ? delegateCacheProvider.DefaultCache
                : delegateCacheProvider.GetNamedCache(name);
        }
            public static DelegateCache FirstCacheNode(Type /*!*/ argType)
            {
                DelegateCache nextCacheNode;

                if (!_delegateCache.TryGetValue(argType, out nextCacheNode))
                {
                    nextCacheNode           = new DelegateCache();
                    _delegateCache[argType] = nextCacheNode;
                }

                return(nextCacheNode);
            }
Esempio n. 15
0
        /// <summary>
        /// Locate specific type using extra data or key
        /// </summary>
        /// <param name="type">type to locate</param>
        /// <param name="extraData">extra data to be used during construction</param>
        /// <param name="consider">filter out exports you don't want to consider</param>
        /// <param name="withKey">key to use for locating type</param>
        /// <param name="isDynamic">skip cache and look through exports</param>
        /// <returns>located instance</returns>
        // ReSharper disable once MethodOverloadWithOptionalParameter
        public override object Locate(Type type, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
        {
            IInjectionContext context = extraData == null ?
                                        null : CreateInjectionContextFromExtraData(type, extraData);

            if (withKey == null && consider == null && !isDynamic)
            {
                return(DelegateCache.ExecuteActivationStrategyDelegateWithContext(type, this, false, context));
            }

            return(InternalLocate(this, this, type, consider, withKey, context, false, isDynamic));
        }
Esempio n. 16
0
        /// <summary>
        /// Generic method to find the specified type and cache the result
        /// </summary>
        /// <param name="type">The type</param>
        /// <param name="cacheResult">Whether to cache the result</param>
        /// <param name="specificAssemblies">Specific assemblies to search within</param>
        /// <returns>The <see cref="IEnumerable{Type}"/></returns>
        public static IEnumerable <Type> ResolveTypes(Type type, bool cacheResult = true, IEnumerable <Assembly> specificAssemblies = null)
        {
            MethodBaseCacheItem key = GetMethodCacheKey(type);

            if (!DelegateCache.TryGetValue(key, out var f))
            {
                f = CreateGenericResolveMethod(ResolveMethod.MakeGenericMethod(type));
                DelegateCache[key] = f;
            }

            return(((Func <bool, IEnumerable <Assembly>, IEnumerable <Type> >)f)(cacheResult, specificAssemblies));
        }
Esempio n. 17
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <param name="other">
 /// An object to compare with this object.
 /// </param>
 /// <returns>
 /// true if the current object is equal to the other parameter; otherwise, false.
 /// </returns>
 public bool Equals(TSelf other)
 {
     if (other == null || GetType() != other.GetType())
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(DelegateCache.EqualsDelegate((TSelf)this, other));
 }
Esempio n. 18
0
 /// <summary>
 /// Converts the <see cref="DbDataReader"/> into an enumerable of data entity object.
 /// </summary>
 /// <typeparam name="TEntity">The data entity type to convert.</typeparam>
 /// <param name="reader">The <see cref="DbDataReader"/> to be converted.</param>
 /// <param name="basedOnFields">Check whether to create a delegate based on the data reader fields.</param>
 /// <returns>An array of data entity objects.</returns>
 internal static IEnumerable <TEntity> ToEnumerable <TEntity>(DbDataReader reader, bool basedOnFields = false)
     where TEntity : class
 {
     if (reader != null && reader.IsClosed == false && reader.HasRows)
     {
         var @delegate = DelegateCache.GetDataReaderToDataEntityDelegate <TEntity>(reader, basedOnFields);
         while (reader.Read())
         {
             yield return(@delegate(reader));
         }
     }
 }
Esempio n. 19
0
 private ResolutionScope(IResolverSelector resolverSelector,
                         IExpressionBuilder expressionBuilder, IContainerContext containerContext,
                         DelegateCache delegateCache, object name)
 {
     this.rootItem            = DisposableItem.Empty;
     this.rootFinalizableItem = FinalizableItem.Empty;
     this.scopedItems         = AvlTree <object> .Empty;
     this.scopedInstances     = AvlTreeKeyValue <Type, object> .Empty;
     this.resolverSelector    = resolverSelector;
     this.expressionBuilder   = expressionBuilder;
     this.containerContext    = containerContext;
     this.Name          = name;
     this.delegateCache = delegateCache;
 }
Esempio n. 20
0
        /// <summary>
        /// try to locate a specific type
        /// </summary>
        /// <param name="type">type to locate</param>
        /// <param name="value">located value</param>
        /// <param name="extraData">extra data to be used during locate</param>
        /// <param name="consider">filter to use during location</param>
        /// <param name="withKey">key to use during locate</param>
        /// <param name="isDynamic">is the request dynamic</param>
        /// <returns>true if export could be located</returns>
        public override bool TryLocate(Type type, out object value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
        {
            if (!isDynamic && withKey == null && consider == null)
            {
                var hashCode = type.GetHashCode();

                value = DelegateCache.ExecuteActivationStrategyDelegateWithContext(type, this, true, extraData == null ? null : CreateContext(extraData));

                return(value != null);
            }

            value = LocateFromParent(type, extraData, consider, withKey, true, isDynamic);

            return(value != null);
        }
Esempio n. 21
0
 public static bool Equals <T>(T self, object other)
 {
     if (other is null)
     {
         return(false);
     }
     if (self.GetType() != other.GetType())
     {
         return(false);
     }
     if (other is T value)
     {
         return(DelegateCache <T> .EqualsDelegate(self, value));
     }
     return(false);
 }
Esempio n. 22
0
        public IEnumerable <TDest> To <TDest>(string flatteningToken = null)
        {
            Func <TSource, TDest> compiledAction = GetCachedDelegate <TDest>(flatteningToken);

            if (compiledAction == null)
            {
                Expression <Func <TSource, TDest> > queryExpression = GetCachedExpression <TDest>(flatteningToken) ?? BuildExpression <TDest>(flatteningToken);

                compiledAction = queryExpression.Compile();

                string cacheKey = GetCacheKey <Func <TSource, TDest> >(flatteningToken);
                DelegateCache.TryAdd(cacheKey, compiledAction);
            }

            return(queryableSource.Select(compiledAction));
        }
Esempio n. 23
0
        public TDest To <TDest>(string flatteningToken = null)
        {
            Func <TSource, TDest> compiledAction = GetCachedDelegate <TDest>(flatteningToken);

            if (compiledAction == null)
            {
                Expression <Func <TSource, TDest> > queryExpression = GetCachedExpression <TDest>(flatteningToken) ?? BuildExpression <TDest>(flatteningToken);

                compiledAction = queryExpression.Compile();

                string key = GetCacheKey <Expression <Func <TSource, TDest> > >(flatteningToken);

                DelegateCache.TryAdd(key, compiledAction);
            }

            return(compiledAction.Invoke(source));
        }
            public DelegateCache NextCacheNode(Type /*!*/ argType)
            {
                Assert.NotNull(argType);

                DelegateCache nextCacheNode;

                if (TypeChain == null)
                {
                    TypeChain = new Dictionary <Type, DelegateCache>();
                }

                if (!TypeChain.TryGetValue(argType, out nextCacheNode))
                {
                    nextCacheNode      = new DelegateCache();
                    TypeChain[argType] = nextCacheNode;
                }

                return(nextCacheNode);
            }
Esempio n. 25
0
            public DelegateCache GetNamedCache(object name)
            {
                var cache = this.NamedCache.GetOrDefaultByValue(name);

                if (cache != null)
                {
                    return(cache);
                }

                var newCache = new DelegateCache();

                if (Swap.SwapValue(ref this.NamedCache, (t1, t2, t3, t4, items) =>
                                   items.AddOrUpdate(t1, t2, false), name, newCache, Constants.DelegatePlaceholder, Constants.DelegatePlaceholder))
                {
                    return(newCache);
                }

                return(this.NamedCache.GetOrDefaultByValue(name) ?? newCache);
            }
Esempio n. 26
0
        public SingleMapper <TSrc, TDest> GetSingleMapper <TSrc, TDest>()
        {
            CompiledDelegate @delegate = null;

            var key = new TypePair(typeof(TSrc), typeof(TDest));

            DelegateCache.TryGetValue(key, out @delegate);

            var mapMethod = @delegate?.SingleTyped as Func <TSrc, TDest, TDest>;

            if (mapMethod == null)
            {
                throw new HappyMapperException(ErrorMessages.MissingMapping(key.SourceType, key.DestinationType));
            }

            var mapper = new SingleMapper <TSrc, TDest>(mapMethod);

            return(mapper);
        }
Esempio n. 27
0
        public IEnumerable <TDest> To <TDest>(IEnumerable <TDest> destination, string keyMemberName = null, string flatteningToken = null, bool clearCollections = false)
        {
            if (destination != null)
            {
                Delegate compiledAction = GetCachedActionOverQueryableDestination <TDest>(keyMemberName, clearCollections, flatteningToken);

                if (compiledAction == null)
                {
                    Expression <Action <TSource, TDest> > queryExpression = GetCachedExpressionOverDestination <TDest>(keyMemberName, clearCollections, flatteningToken) ?? BuildExpressionOverDestination <TDest>(clearCollections, keyMemberName, flatteningToken);

                    ParameterExpression srcMemberExp = Expression.Parameter(queryableSource.GetType(), name: "src");

                    ParameterExpression dstMemberExp = Expression.Parameter(destination.GetType(), name: "dst");

                    Expression projectEnumerableOverEnumerableExpression = ProjectEnumerableOverEnumerable(typeof(TSource),
                                                                                                           typeof(TDest),
                                                                                                           srcMemberExp,
                                                                                                           dstMemberExp,
                                                                                                           keyMemberName,
                                                                                                           clearCollections,
                                                                                                           flatteningToken,
                                                                                                           new List <string>());

                    Type builtDelegateType = typeof(Action <,>).MakeGenericType(queryableSource.GetType(), destination.GetType());

                    LambdaExpression lambda = Expression.Lambda(builtDelegateType, projectEnumerableOverEnumerableExpression, srcMemberExp, dstMemberExp);

                    compiledAction = lambda.Compile();

                    string key = GetCacheKey <Delegate>(flatteningToken, keyMemberName, clearCollections);
                    DelegateCache.TryAdd(key, compiledAction);
                }

                compiledAction.DynamicInvoke(queryableSource, destination);
            }
            else
            {
                return(this.To <TDest>(flatteningToken));
            }
            return(destination);
        }
Esempio n. 28
0
        /// <summary>
        /// 按服务名称,随机返回一个服务地址
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="minute"></param>
        /// <returns></returns>
        public CatalogService GetServiceInfo(string serviceName, bool passingOnly = false, double minute = 0)
        {
            List <CatalogService> all;

            if (minute > 0)
            {
                all = DelegateCache.Init("consulServiceCache", minute, () =>
                {
                    return(GetService(serviceName, passingOnly));
                });
            }
            else
            {
                all = GetService(serviceName, passingOnly);
            }
            if (all.Count == 0)
            {
                throw new Exception($"找不到可用的服务:{serviceName}");
            }
            int k = rng.Next(all.Count);

            return(all[k]);
        }
Esempio n. 29
0
        public SimpleHandlerDispatchDelegateCacheProvider()
        {
            Type bridgeType = typeof(BridgeType);

            // PcTyped
            MethodInfo callPcTypedEventSubscriber_mi = bridgeType.GetMethod("CallPcTypedEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPcTypedEventSubsCache = new TwoTypesDelegateCache <CallPcTypedEventSubscriberDelegate>(callPcTypedEventSubscriber_mi);

            // PcGen
            MethodInfo callPcGenEventSubscriber_mi = bridgeType.GetMethod("CallPcGenEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPcGenEventSubsCache = new DelegateCache <CallPcGenEventSubscriberDelegate>(callPcGenEventSubscriber_mi);

            // PcObject
            MethodInfo callPcObjEventSubscriber_mi = bridgeType.GetMethod("CallPcObjectEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPcObjEventSubsCache = new DelegateCache <CallPcObjEventSubscriberDelegate>(callPcObjEventSubscriber_mi);

            // PcStandard
            MethodInfo callPcStEventSubscriber_mi = bridgeType.GetMethod("CallPcStEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPcStEventSubsCache = new DelegateCache <CallPcStandardEventSubscriberDelegate>(callPcStEventSubscriber_mi);

            // PcChanging
            MethodInfo callPChangingEventSubscriber_mi = bridgeType.GetMethod("CallPChangingEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPChangingEventSubsCache = new DelegateCache <CallPChangingEventSubscriberDelegate>(callPChangingEventSubscriber_mi);

            // PropStoreNode Parent Changed
            MethodInfo callPSNodeParentChangedEventSubscriber_mi = bridgeType.GetMethod("CallPSNodeParentChangedEventSubscriber", BindingFlags.Instance | BindingFlags.NonPublic);

            _callPSParentNodeChangedEventSubsCache = new DelegateCache <CallPSParentNodeChangedEventSubDelegate>(callPSNodeParentChangedEventSubscriber_mi);

            // Proxy -- Holds a copy of the original delegate but without the target.
            _delegateProxyCache = new DelegateProxyCache();
        }
Esempio n. 30
0
 private ResolutionScope(IResolverSelector resolverSelector, IExpressionBuilder expressionBuilder,
                         IContainerContext containerContext, IResolutionScope rootScope, IResolutionScope parent, DelegateCache delegateCache, object name = null)
     : this(resolverSelector, expressionBuilder, containerContext, delegateCache, name)
 {
     this.RootScope   = rootScope;
     this.ParentScope = parent;
 }