Example #1
0
        /// <summary>
        /// 创建实现了指定接口的HttpApiClient实例
        /// </summary>
        /// <param name="interfaceType">请求接口类型</param>
        /// <param name="apiInterceptor">http接口调用拦截器</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="TypeLoadException"></exception>
        /// <returns></returns>
        public static HttpApiClient Create(Type interfaceType, IApiInterceptor apiInterceptor)
        {
            if (interfaceType == null)
            {
                throw new ArgumentNullException(nameof(interfaceType));
            }

            if (apiInterceptor == null)
            {
                throw new ArgumentNullException(nameof(apiInterceptor));
            }

            return(HttpApiClientProxy.CreateInstance(interfaceType, apiInterceptor));
        }
Example #2
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) =>
            {
                return(AssemblyBuilder
                       .DefineDynamicAssembly(new AssemblyName(hash.ToString()), AssemblyBuilderAccess.Run)
                       .DefineDynamicModule(moduleName));
            });

            var typeBuilder = moduleBuilder.DefineType(interfaceType.FullName, TypeAttributes.Class, typeof(HttpApiClient));

            typeBuilder.AddInterfaceImplementation(interfaceType);

            var proxyType = HttpApiClientProxy.ImplementApiMethods(typeBuilder, apiMethods);

            return(proxyType.GetConstructor(proxyTypeCtorArgTypes));
        }