Beispiel #1
0
        private MethodOptions(
            Dictionary <string, ICompressionProvider> compressionProviders,
            InterceptorCollection interceptors,
            int?maxSendMessageSize,
            int?maxReceiveMessageSize,
            bool?enableDetailedErrors,
            string?responseCompressionAlgorithm,
            CompressionLevel?responseCompressionLevel)
        {
            CompressionProviders         = compressionProviders;
            Interceptors                 = interceptors;
            HasInterceptors              = interceptors.Count > 0;
            MaxSendMessageSize           = maxSendMessageSize;
            MaxReceiveMessageSize        = maxReceiveMessageSize;
            EnableDetailedErrors         = enableDetailedErrors;
            ResponseCompressionAlgorithm = responseCompressionAlgorithm;
            ResponseCompressionLevel     = responseCompressionLevel;

            if (ResponseCompressionAlgorithm != null)
            {
                if (!CompressionProviders.TryGetValue(ResponseCompressionAlgorithm, out var _))
                {
                    throw new InvalidOperationException($"The configured response compression algorithm '{ResponseCompressionAlgorithm}' does not have a matching compression provider.");
                }
            }
        }
Beispiel #2
0
        private MethodContext CreateMethodContext <TRequest, TResponse>()
        {
            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            var resolvedCompressionProviders = new Dictionary <string, ICompressionProvider>(StringComparer.Ordinal);

            AddCompressionProviders(resolvedCompressionProviders, _serviceOptions._compressionProviders);
            AddCompressionProviders(resolvedCompressionProviders, _globalOptions._compressionProviders);

            var interceptors = new InterceptorCollection();

            interceptors.AddRange(_globalOptions.Interceptors);
            interceptors.AddRange(_serviceOptions.Interceptors);

            return(new MethodContext
                   (
                       requestType: typeof(TRequest),
                       responseType: typeof(TResponse),
                       compressionProviders: resolvedCompressionProviders,
                       interceptors: interceptors,
                       maxSendMessageSize: _serviceOptions.MaxSendMessageSize ?? _globalOptions.MaxSendMessageSize,
                       maxReceiveMessageSize: _serviceOptions.MaxReceiveMessageSize ?? _globalOptions.MaxReceiveMessageSize,
                       enableDetailedErrors: _serviceOptions.EnableDetailedErrors ?? _globalOptions.EnableDetailedErrors,
                       responseCompressionAlgorithm: _serviceOptions.ResponseCompressionAlgorithm ?? _globalOptions.ResponseCompressionAlgorithm,
                       responseCompressionLevel: _serviceOptions.ResponseCompressionLevel ?? _globalOptions.ResponseCompressionLevel
                   ));
        }
Beispiel #3
0
        public static InterceptorCollection AddMethodMetric(this InterceptorCollection interceptor,
                                                            Assembly[] ass,
                                                            Func <MethodInfo, bool> force_include = null,
                                                            Func <MethodInfo, bool> except        = null)
        {
            except ??= (x => false);
            force_include ??= (x => false);

            bool __filter__(MethodInfo x)
            {
                if (x.GetCustomAttributes <WCloud.Core.Apm.ApmAttribute>().Any() || force_include.Invoke(x))
                {
                    return(true);
                }
                if ((!ass.Contains(x.DeclaringType.Assembly)) || except.Invoke(x))
                {
                    return(false);
                }
                return(true);
            }

            //这里的x是接口定义不是实现
            interceptor.AddTyped <MethodCallMetricAttribute>(x => __filter__(x));

            return(interceptor);
        }
        /// <summary>
        /// Compile IQueryPartsContainer to a QueryString
        /// </summary>
        /// <param name="container">The container containing all queryparts to compile to sql</param>
        /// <param name="interceptors">The collection of interceptors</param>
        /// <returns>The Compiled query</returns>
        public virtual CompiledQuery Compile(IQueryPartsContainer container, InterceptorCollection interceptors)
        {
            _compiledParts = new HashSet<IQueryPart>();

            if (container.AggregatePart != null)
            {
                var interception = new InterceptionHandler(interceptors, container.AggregatePart.EntityType);
                interception.ExecuteBeforeCompile(container);
            }

            using (var writer = new StringWriter())
            {
                foreach (var part in container.Parts)
                {
                    CompilePart(part, writer, container);
                }

                var query = writer.ToString();

                return new CompiledQuery
                {
                    QueryString = query,
                    QueryParts = container
                };
            }
        }
Beispiel #5
0
        public static InterceptorCollection ConfigureEFInterceptors(this InterceptorCollection interceptorCollection)
        {
            //由于EF自动生成的迁移类会寻找DbContext派生类所在的命名空间,当启用AspectCore的AOP功能后DbContext将会被代理到AspectCore中
            //暂时注释掉
            //interceptorCollection.AddTyped<EFInterceptor>(Predicates.ForMethod("*DbContext", "OnModelCreating"));

            return(interceptorCollection);
        }
 public static InterceptorCollection AddRequestExecuted(this InterceptorCollection interceptors, Func <RequestExecutedContext, Task> invoker)
 {
     interceptors.AddRequestExecution(async(_, next) =>
     {
         var context = await next();
         await invoker(context);
     });
     return(interceptors);
 }
        public void Interceptor_AddInterceptorTwiceTest()
        {
            var collection = new InterceptorCollection();
            var orig = new Interceptor<Order>();
            collection.Add(orig);
            var second = collection.Add(new Interceptor<Order>());

            Assert.AreNotSame(orig, second);
        }
        public void Interceptor_AddInterceptorTest()
        {
            var collection = new InterceptorCollection();
            var orig = new Interceptor<Order>();
            collection.Add(orig);

            var reference = collection.GetInterceptor<Order>();

            Assert.AreSame(orig, reference);
        }
        public void Interceptor_GetInterceptorOfTTest()
        {
            var collection = new InterceptorCollection();
            var first = collection.Add(new Interceptor<Order>());
            collection.Add(new Interceptor<Bill>());
            collection.Add(new Interceptor<Order>());

            var order = collection.GetInterceptor<Order>();

            Assert.AreSame(first, order);
        }
        public void Add_GenericInterceptorBaseType_AddedToCollection()
        {
            // Arrange
            var interceptors = new InterceptorCollection();

            // Act
            var ex = Assert.Throws <ArgumentException>(() => interceptors.Add <Interceptor>()) !;

            // Assert
            Assert.AreEqual("Type must inherit from Grpc.Core.Interceptors.Interceptor. (Parameter 'interceptorType')", ex.Message);
        }
        public void Interceptor_GetInterceptorsOfTTest()
        {
            var collection = new InterceptorCollection();
            var first = collection.Add(new Interceptor<Order>());
            collection.Add(new Interceptor<Bill>());
            var seccond = collection.Add(new Interceptor<Order>());

            var orders = collection.GetInterceptors<Order>();

            Assert.AreSame(first, orders.First());
            Assert.AreSame(seccond, orders.Last());
        }
    public FluentAspectConfiguration()
    {
        ThrowAspectException = true;
        ValidationHandlers   = new AspectValidationHandlerCollection();
        Interceptors         = new InterceptorCollection();
        NonAspectPredicates  = new NonAspectPredicateCollection();

        ValidationHandlers.Add(new OverwriteAspectValidationHandler());
        ValidationHandlers.Add(new AttributeAspectValidationHandler());
        ValidationHandlers.Add(new CacheAspectValidationHandler());
        ValidationHandlers.Add(new ConfigureAspectValidationHandler(this));
    }
        public void QueryKernel_InterceptBeforeExecuteTest()
        {
            var query = string.Empty;

            var interceptors = new InterceptorCollection();
            interceptors.Add(new Interceptor<Warrior>().BeforeExecute(qc => query = qc.QueryString));
            var kernel = new QueryKernel(_provider.Object, _settings.Object, interceptors);

            // Act
            var items = kernel.Execute<Warrior>(new CompiledQuery { QueryString = "Mocked Query" });

            Assert.AreEqual(query, "Mocked Query");
        }
        public void Add_Generic_AddedToCollection()
        {
            // Arrange
            var interceptors = new InterceptorCollection();

            // Act
            interceptors.Add <TestInterceptor>();

            // Assert
            Assert.AreEqual(1, interceptors.Count);
            Assert.AreEqual(typeof(TestInterceptor), interceptors[0].Type);
            Assert.AreEqual(0, interceptors[0].Arguments.Count);
        }
Beispiel #15
0
        private static void Init()
        {
            var container = new ServiceContainer();

            container.AddType <CustomService>();
            container.AddType <ILogger, ConsoleLogger>();
            container.AddType <ICustomService, CustomService>();

            DependencyResolver.SetDependencyResolver(container.Build());

            var interceptorCollection = new InterceptorCollection();

            interceptorCollection.AddTyped <CustomInterceptorAttribute>();
        }
        internal static void AddErrorHandler(
            InterceptorCollection interceptors,
            Func <IServiceProvider, IServerErrorHandler>?errorHandlerFactory,
            IMarshallerFactory?marshallerFactory)
        {
            if (errorHandlerFactory != null)
            {
                var factory = new ErrorHandlerServerCallInterceptorFactory(
                    marshallerFactory.ThisOrDefault(),
                    errorHandlerFactory);

                interceptors.Add <ServerNativeInterceptor>(factory);
            }
        }
        public void Add_NonGenericWithArgs_AddedToCollection()
        {
            // Arrange
            var interceptors = new InterceptorCollection();

            // Act
            interceptors.Add(typeof(TestInterceptor), "Arg");

            // Assert
            Assert.AreEqual(1, interceptors.Count);
            Assert.AreEqual(typeof(TestInterceptor), interceptors[0].Type);
            Assert.AreEqual(1, interceptors[0].Arguments.Count);
            Assert.AreEqual("Arg", interceptors[0].Arguments[0]);
        }
Beispiel #18
0
        /// <summary>
        /// Creates method options by merging together the settings the specificed <see cref="GrpcServiceOptions"/> collection.
        /// The <see cref="GrpcServiceOptions"/> should be ordered with items arranged in ascending order of precedence.
        /// When interceptors from multiple options are merged together they will be executed in reverse order of precendence.
        /// </summary>
        /// <param name="serviceOptions">A collection of <see cref="GrpcServiceOptions"/> instances, arranged in ascending order of precedence.</param>
        /// <returns>A new <see cref="MethodOptions"/> instanced with settings merged from specifid <see cref="GrpcServiceOptions"/> collection.</returns>
        public static MethodOptions Create(IEnumerable <GrpcServiceOptions> serviceOptions)
        {
            // This is required to get ensure that service methods without any explicit configuration
            // will continue to get the global configuration options
            var              resolvedCompressionProviders    = new Dictionary <string, ICompressionProvider>(StringComparer.Ordinal);
            var              tempInterceptors                = new List <InterceptorRegistration>();
            int?             maxSendMessageSize              = null;
            var              maxSendMessageSizeConfigured    = false;
            int?             maxReceiveMessageSize           = GrpcServiceOptionsSetup.DefaultReceiveMaxMessageSize;
            var              maxReceiveMessageSizeConfigured = false;
            bool?            enableDetailedErrors            = null;
            string?          responseCompressionAlgorithm    = null;
            CompressionLevel?responseCompressionLevel        = null;

            foreach (var options in serviceOptions.Reverse())
            {
                AddCompressionProviders(resolvedCompressionProviders, options.CompressionProviders);
                tempInterceptors.InsertRange(0, options.Interceptors);
                if (!maxSendMessageSizeConfigured && options._maxSendMessageSizeConfigured)
                {
                    maxSendMessageSize           = options.MaxSendMessageSize;
                    maxSendMessageSizeConfigured = true;
                }
                if (!maxReceiveMessageSizeConfigured && options._maxReceiveMessageSizeConfigured)
                {
                    maxReceiveMessageSize           = options.MaxReceiveMessageSize;
                    maxReceiveMessageSizeConfigured = true;
                }
                enableDetailedErrors ??= options.EnableDetailedErrors;
                responseCompressionAlgorithm ??= options.ResponseCompressionAlgorithm;
                responseCompressionLevel ??= options.ResponseCompressionLevel;
            }

            var interceptors = new InterceptorCollection();

            interceptors.AddRange(tempInterceptors);

            return(new MethodOptions
                   (
                       compressionProviders: resolvedCompressionProviders,
                       interceptors: interceptors,
                       maxSendMessageSize: maxSendMessageSize,
                       maxReceiveMessageSize: maxReceiveMessageSize,
                       enableDetailedErrors: enableDetailedErrors,
                       responseCompressionAlgorithm: responseCompressionAlgorithm,
                       responseCompressionLevel: responseCompressionLevel
                   ));
        }
 public DefaultInterceptionValidator(InterceptorCollection collections)
 {
     _collections = collections ?? throw new ArgumentNullException(nameof(collections));
 }
 public InterceptedUnaryServerCallHandlerBenchmark()
 {
     Interceptors = new InterceptorCollection();
     Interceptors.Add <UnaryAwaitInterceptor>();
 }
        public static InterceptorCollection ConfigureEFInterceptors(this InterceptorCollection interceptorCollection)
        {
            interceptorCollection.AddTyped <EFInterceptor>(Predicates.ForMethod("*DbContext", "OnModelCreating"));

            return(interceptorCollection);
        }
 public static InterceptorCollection AddException(this InterceptorCollection interceptors, Func <ExceptionInterceptorContext, Task> invoker)
 {
     interceptors.Add(new SimpleInterceptor(invoker));
     return(interceptors);
 }
Beispiel #23
0
 public GoOptions()
 {
     Interceptors = new InterceptorCollection();
     Conventions  = new List <IGoModelConvention>();
     Types        = new List <Type>();
 }
 public DefaultInterceptorInvoker(InterceptorCollection collection)
 {
     _collections = collection ?? throw new ArgumentNullException(nameof(collection));
 }
        public void QueryKernel_InterceptExecuteTest()
        {
            var warriors = new List<Warrior>
            {
                new Warrior()
            };

            var interceptors = new InterceptorCollection();
            interceptors.Add(new Interceptor<Warrior>().AsExecute(qc => warriors));
            var kernel = new QueryKernel(_provider.Object, _settings.Object, interceptors);

            // Act
            var items = kernel.Execute<Warrior>(new CompiledQuery());

            Assert.AreSame(items.First(), warriors.First());
        }
Beispiel #26
0
        public static InterceptorCollection InterceptorServiceMethods <InterceptorType>(this InterceptorCollection interceptor,
                                                                                        Assembly[] ass, Func <MethodInfo, bool> excludeFilter = null)
            where InterceptorType : class, AspectCore.DynamicProxy.IInterceptor
        {
            excludeFilter ??= (x => false);

            bool __filter__(MethodInfo x)
            {
                if (!ass.Contains(x.DeclaringType.Assembly))
                {
                    return(false);
                }
                if (excludeFilter.Invoke(x))
                {
                    return(false);
                }
                return(true);
            }

            //这里的x是接口定义不是实现
            interceptor.AddTyped <InterceptorType>(x => __filter__(x));

            return(interceptor);
        }
 public SqlDatabaseContext(IConnectionProvider provider, ISettings settings, InterceptorCollection interceptors)
     : base(provider, settings, interceptors)
 {
 }
 public static InterceptorCollection AddRequestExecution(this InterceptorCollection interceptors, Func <RequestExecutingContext, RequestExecutionDelegate, Task> execution)
 {
     interceptors.Add(new SimpleInterceptor(execution));
     return(interceptors);
 }
 public InterceptorPipelineBuilder(InterceptorCollection interceptors)
 {
     _interceptors = interceptors;
 }
Beispiel #30
0
 public InterceptorPipelineBuilder(InterceptorCollection interceptors, IServiceProvider serviceProvider)
 {
     _interceptors    = interceptors;
     _serviceProvider = serviceProvider;
 }