Example #1
0
        /// <summary>
        /// 创建接口的代理实例
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <param name="interceptor">拦截器</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <returns></returns>
        public static T CreateInterfaceProxyWithoutTarget <T>(IInterceptor interceptor) where T : class
        {
            var interfaceType = typeof(T);
            var apiMethods    = interfaceType.GetApiAllMethods();
            var proxyTypeCtor = proxyTypeCtorCache.GetOrAdd(interfaceType, type => GenerateProxyTypeCtor(type, apiMethods));

            return(proxyTypeCtor.Invoke(new object[] { interceptor, apiMethods }) as T);
        }
Example #2
0
        public static T Create <T>(string apiUrl)
        {
            var client = clientCache.GetOrAdd(apiUrl, (url) => new HttpClient()
            {
                BaseAddress = new Uri(url)
            });

            return(ProxyGenerator.Create <T>(new HttpClientProxy(client)));
        }
Example #3
0
 /// <summary>
 /// 从类型的属性获取Setter
 /// </summary>
 /// <param name="type">类型</param>
 /// <returns></returns>
 public static PropertySetter[] GetPropertySetters(Type type)
 {
     return(cached.GetOrAdd(type, t => t.GetProperties()
                            .Where(p => p.CanWrite)
                            .Select(p => new PropertySetter(p))
                            .ToArray()));
 }
Example #4
0
        public static bool IsUriParameterType(this Type parameterType)
        {
            return(cache.GetOrAdd(parameterType, type =>
            {
                if (type == null)
                {
                    return false;
                }

                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments().FirstOrDefault();
                }

                if (type.IsPrimitive || parameterType.IsEnum)
                {
                    return true;
                }

                return type == typeof(string) ||
                type == typeof(decimal) ||
                type == typeof(DateTime) ||
                type == typeof(Guid) ||
                type == typeof(Uri);
            }));
        }
Example #5
0
            /// <summary>
            /// 访问成员时
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            protected override Expression VisitMember(MemberExpression node)
            {
                var name = staticNameCache.GetOrAdd(node.Member, m => this.nameFunc(m));

                this.path.Insert(0, $"/{name}");
                return(base.VisitMember(node));
            }
Example #6
0
        /// <summary>
        /// Instantiates the specified ctor arguments.
        /// </summary>
        /// <param name="ctor">The ctor.</param>
        /// <param name="ctorArgs">The ctor arguments.</param>
        /// <returns></returns>
        public static object Instantiate(this ConstructorInfo ctor, object[] ctorArgs)
        {
            Func <object[], object> factory;

            factory = factories.GetOrAdd(ctor, BuildFactory);

            return(factory.Invoke(ctorArgs));
        }
            /// <summary>
            /// 访问成员时
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            protected override Expression VisitMember(MemberExpression node)
            {
                var name = nameCache.GetOrAdd(node.Member, m => this.nameFunc(m));

                if (this.camelCase == true)
                {
                    name = FormatOptions.CamelCase(name);
                }

                this.path.Insert(0, $"/{name}");
                return(base.VisitMember(node));
            }
Example #8
0
        /// <summary>
        /// 返回类型的默认值
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object DefaultValue(this Type type)
        {
            if (type == null)
            {
                return(null);
            }

            return(typeDefaultValueCache.GetOrAdd(type, t =>
            {
                var value = Expression.Convert(Expression.Default(t), typeof(object));
                return Expression.Lambda <Func <object> >(value).Compile().Invoke();
            }));
        }
Example #9
0
 public void RegisterType(Type interfaceConstract, Type constractService)
 {
     if (constractService != null && interfaceConstract != null)
     {
         if (!constractService.IsAbstract && !constractService.IsInterface && interfaceConstract.IsAssignableFrom(constractService))
         {
             IocUnity.AddTransient(interfaceConstract, constractService);
             ConstractInterfaceCache.GetOrAdd(interfaceConstract.FullName, key =>
             {
                 return(interfaceConstract);
             });
             AddRouteKey(interfaceConstract.FullName);
         }
     }
 }
Example #10
0
        /// <summary>
        /// 返回ITokenClient的客户端实例
        /// </summary>
        /// <param name="tokenEndpoint">授权服务器地址</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns></returns>
        public static ITokenToken Get(Uri tokenEndpoint)
        {
            if (tokenEndpoint == null)
            {
                throw new ArgumentNullException(nameof(tokenEndpoint));
            }

            return(cache.GetOrAdd(tokenEndpoint, endpoint =>
            {
                var config = new HttpApiConfig {
                    HttpHost = endpoint
                };
                return HttpApiClient.Create <ITokenToken>(config);
            }));
        }
Example #11
0
        /// <summary>
        /// 生成接口的代理类 返回其构造器
        /// </summary>
        /// <param name="interfaceType">接口类型</param>
        /// <param name="apiMethods">拦截的方法</param>
        /// <returns></returns>
        private static ConstructorInfo GenerateProxyTypeCtor(Type interfaceType, MethodInfo[] apiMethods)
        {
            var moduleName = interfaceType.Module.Name;
            var hashCode   = interfaceType.Assembly.GetHashCode() ^ interfaceType.Module.GetHashCode();

            // 每个动态集下面只会有一个模块
            var moduleBuilder = hashCodeModuleBuilderCache.GetOrAdd(hashCode, hash => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(hash.ToString()), AssemblyBuilderAccess.Run).DefineDynamicModule(moduleName));
            var typeBuilder   = moduleBuilder.DefineType(interfaceType.FullName, TypeAttributes.Class);

            typeBuilder.AddInterfaceImplementation(interfaceType);

            var proxyType = ImplementApiMethods(typeBuilder, apiMethods);

            return(proxyType.GetConstructor(proxyTypeCtorArgTypes));
        }
Example #12
0
        /// <summary>
        /// 返回是否需要进行属性验证
        /// </summary>
        /// <param name="instance">实例</param>
        /// <returns></returns>
        private static bool IsNeedValidateProperty(object instance)
        {
            if (instance == null)
            {
                return(false);
            }

            var type = instance.GetType();

            if (type == typeof(string) || type.GetTypeInfo().IsValueType == true)
            {
                return(false);
            }

            return(cache.GetOrAdd(type, t => t.GetProperties().Any(p => p.CanRead && p.IsDefined(typeof(ValidationAttribute), true))));
        }
Example #13
0
 public virtual IEnumerable <Event> GetEvents <TKey>(TKey eventId, int afterVersion = 0)
     where TKey : IEquatable <TKey>
 {
     return(_eventsDict.GetOrAdd(eventId.ToString(), x =>
     {
         var storeEvents = EventStorageRepository.GetEvents(eventId, afterVersion);
         var eventlist = new ConcurrentBag <Event>();
         foreach (var e in storeEvents)
         {
             var eventType = Type.GetType(e.EventType);
             eventlist.Add(JsonConvert.DeserializeObject(e.Data, eventType) as Event);
         }
         return eventlist;
     })
            .Where(e => e.Version >= afterVersion).OrderBy(e => e.Timestamp));
 }
Example #14
0
        /// <summary>
        /// 返回HttpApiClient代理类的实例
        /// </summary>
        /// <param name="interfaceType">接口类型</param>
        /// <param name="interceptor">拦截器</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <returns></returns>
        public static object CreateInstance(Type interfaceType, IApiInterceptor interceptor)
        {
            // 接口的实现在动态程序集里,所以接口必须为public修饰才可以创建代理类并实现此接口
            if (interfaceType.GetTypeInfo().IsVisible == false)
            {
                var message = $"WebApiClient.JIT不支持非public接口定义:{interfaceType}";
                throw new NotSupportedException(message);
            }

            var apiMethods    = interfaceType.GetAllApiMethods();
            var proxyTypeCtor = proxyTypeCtorCache.GetOrAdd(
                interfaceType,
                @interface => @interface.ImplementAsHttpApiClient(apiMethods));

            return(proxyTypeCtor.Invoke(new object[] { interceptor, apiMethods }));
        }
Example #15
0
        public void GetOrAddGet()
        {
            var key   = "WebApiClient";
            var cache = new ConcurrentCache <string, int>();

            Parallel.For(0, 1000, (i) =>
            {
                var value = cache.GetOrAdd(key, k =>
                {
                    Interlocked.Increment(ref this.count);
                    return(1);
                });

                Assert.True(value == 1);
                Assert.True(count == 1);
            });
        }
Example #16
0
        public object CallAction(ActionSerDes actionDes)
        {
            MethodInfo callMethodInfo = null;
            Type       actionType     = ConstractInterfaceCache.Get(actionDes.TargetTypeFullName);
            dynamic    serviceValue   = IocUnity.Get(actionType);
            string     actionKey      = actionDes.GetRouteAddress();

            callMethodInfo = ActionMethodInfoCache.GetOrAdd(actionKey, key =>
            {
                var sameNameMethodList = actionType.GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(f => f.Name == actionDes.MethodName).ToList();
                MethodInfo methodInfo  = null;
                //只区分参数个数不区分类型
                if (sameNameMethodList.Count == 1)
                {
                    methodInfo = sameNameMethodList.FirstOrDefault();
                }
                else
                {
                    methodInfo = sameNameMethodList.FirstOrDefault(f => f.GetParameters().Length == actionDes.ParamterInfoArray.Length);
                }
                return(methodInfo);
            });
            if (callMethodInfo == null)
            {
                throw new KeyNotFoundException($"路由地址没有找到【{actionKey}】!");
            }

            var    actionParamters = actionDes.GetParamters(callMethodInfo);
            object rtnObj          = null;

            try
            {
                var dynamicDelegate = DynamicMethodTool.GetMethodInvoker(callMethodInfo);
                rtnObj = dynamicDelegate(serviceValue, actionParamters);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.ToString());
                throw;
            }

            return(rtnObj);
        }
Example #17
0
        public void Publish <TEvent>(TEvent @event) where TEvent : Event
        {
            if (@event == null)
            {
                return;
            }

            var eventQueue = eventQueueDict.GetOrAdd(@event.EventId, new ConcurrentQueue <Event>());

            eventQueue.Enqueue(@event);

            if (!taskDict.TryGetValue(@event.EventId, out Task task) || task.IsCompleted || task.IsCanceled || task.IsFaulted)
            {
                task?.Dispose();

                taskDict[@event.EventId] = Task.Run(() =>
                {
                    while (!eventQueue.IsEmpty && eventQueue.TryDequeue(out var evt))
                    {
                        messageProcessor.Send(evt);
                    }
                });
            }
        }
Example #18
0
        /// <summary>
        /// 获取接口类型及其继承的接口的所有方法
        /// </summary>
        /// <param name="interfaceType">接口类型</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <returns></returns>
        public static MethodInfo[] GetApiAllMethods(this Type interfaceType)
        {
            if (interfaceType.IsInterface == false)
            {
                throw new ArgumentException("类型必须为接口类型");
            }

            // 接口的实现在动态程序集里,所以接口必须为public修饰才可以创建代理类并实现此接口
            var attrs = new[] { TypeAttributes.Public, TypeAttributes.NestedPublic };
            var attr  = attrs.Aggregate((a, b) => a | b) & interfaceType.Attributes;

            if (attrs.Contains(attr) == false)
            {
                throw new NotSupportedException(interfaceType.Name + "必须为public修饰");
            }

            return(interfaceMethodsCache.GetOrAdd(interfaceType, type =>
            {
                var typeHashSet = new HashSet <Type>();
                var methodHashSet = new HashSet <MethodInfo>();
                GetInterfaceMethods(type, ref typeHashSet, ref methodHashSet);
                return methodHashSet.ToArray();
            }));
        }
Example #19
0
 public void ConcurrentCache_GetOrAdd()
 {
     cache.GetOrAdd(typeof(Benchmark), key => string.Empty);
 }
Example #20
0
 /// <summary>
 /// 获取api的描述
 /// 默认实现使用了缓存
 /// </summary>
 /// <param name="method">接口的方法</param>
 /// <param name="parameters">参数值集合</param>
 /// <returns></returns>
 protected virtual ApiActionDescriptor GetApiActionDescriptor(MethodInfo method, object[] parameters)
 {
     return(descriptorCache.GetOrAdd(method, m => this.CreateApiActionDescriptor(m)).Clone(parameters));
 }
Example #21
0
 /// <summary>
 /// 从类型获取KeyValuePairReader
 /// </summary>
 /// <param name="type">类型</param>
 /// <returns></returns>
 public static KeyValuePairReader GetReader(Type type)
 {
     return(readerCache.GetOrAdd(type, t => new KeyValuePairReader(t)));
 }
Example #22
0
 public static bool IsUriParameterTypeArray(this Type parameterType)
 {
     return(arrCache.GetOrAdd(parameterType, type => type.BaseType == typeof(Array) &&
                              type.GetElementType().IsUriParameterType()));
 }
Example #23
0
 /// <summary>
 /// 获取接口类型及其继承的接口的所有方法
 /// 忽略HttpApiClient类型的所有接口的方法
 /// </summary>
 /// <param name="interfaceType">接口类型</param>
 /// <exception cref="ArgumentException"></exception>
 /// <exception cref="NotSupportedException"></exception>
 /// <returns></returns>
 public static MethodInfo[] GetAllApiMethods(this Type interfaceType)
 {
     return(interfaceMethodsCache.GetOrAdd(
                interfaceType,
                type => type.GetAllApiMethodsNoCache()));
 }
Example #24
0
 /// <summary>
 /// 关联的AttributeUsageAttribute是否AllowMultiple
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static bool AllowMultiple(this Type type)
 {
     return(typeAllowMultipleCache.GetOrAdd(type, (t => t.IsInheritFrom <Attribute>() && t.GetAttribute <AttributeUsageAttribute>(true).AllowMultiple)));
 }
Example #25
0
 /// <summary>
 /// 从类型的属性获取属性
 /// </summary>
 /// <param name="type">类型</param>
 /// <returns></returns>
 public static Property[] GetProperties(Type type)
 {
     return(cached.GetOrAdd(type, t => t.GetProperties().Select(p => new Property(p)).ToArray()));
 }