public bool TryRelate(AspectContext context, IInterceptor interceptor)
        {
            if (interceptor == null || context == null)
            {
                return(false);
            }
            if (!(interceptor is IScopeInterceptor scopedInterceptor))
            {
                return(true);
            }
            if (scopedInterceptor.Scope == Scope.None)
            {
                return(true);
            }
            var currentContexts = GetCurrentContextsInternal(context).ToArray();

            if (currentContexts.Length == 0)
            {
                return(true);
            }
            if (scopedInterceptor.Scope == Scope.Nested)
            {
                var preContext = currentContexts[currentContexts.Length - 1];
                return(!TryInlineImpl(preContext));
            }

            foreach (var current in currentContexts)
            {
                if (TryInlineImpl(current))
                {
                    return(false);
                }
            }

            return(true);

            IEnumerable <AspectContext> GetCurrentContextsInternal(AspectContext ctx)
            {
                foreach (var current in GetCurrentContexts())
                {
                    if (current == ctx)
                    {
                        break;
                    }
                    yield return(current);
                }
            }

            bool TryInlineImpl(AspectContext ctx)
            {
                return(_interceptorCollector.
                       Collect(ctx.ServiceMethod, ctx.ImplementationMethod).
                       Where(x => x.GetType() == interceptor.GetType()).
                       Any(x => TryRelate(ctx, x)));
            }
        }
示例#2
0
        private string GetName(IInterceptor interceptor)
        {
            if (interceptor is Interceptor)
            {
                var count = Interceptors.Values.Count(x => x.Interceptor is Interceptor);
                return($"Interceptor{count}");
            }

            return(interceptor.GetType().Name);
        }
示例#3
0
        /// <summary>
        /// Registers the interceptor. Mutiple interceptors of the same type can
        /// be registered. They will be executed in registration order.
        /// </summary>
        /// <param name="interceptor">Interceptor to register.</param>
        public void RegisterInterceptor(IInterceptor interceptor)
        {
            List <IInterceptor> list;
            var interceptorType = GetInterceptorType(interceptor.GetType());

            if (!interceptors.TryGetValue(interceptorType, out list))
            {
                list = new List <IInterceptor>();
                interceptors[interceptorType] = list;
            }

            list.Add(interceptor);
        }
 private void CheckRequiredMixins(MethodBase baseMethod, IList methodinterceptors)
 {
     foreach (object unknownInterceptor in methodinterceptors)
     {
         if (unknownInterceptor is IInterceptor)
         {
             IInterceptor interceptor = unknownInterceptor as IInterceptor;
             foreach (RequiresMixinAttribute requiresMixinAttribute in interceptor.GetType().GetCustomAttributes(typeof(RequiresMixinAttribute), true))
             {
                 foreach (Type requiredMixinType in requiresMixinAttribute.Types)
                 {
                     bool  hasMixin = false;
                     IList mixins   = (IList)mixinsForType[baseMethod.DeclaringType];
                     if (mixins != null)
                     {
                         foreach (Type mixinType in mixins)
                         {
                             if (requiredMixinType.IsAssignableFrom(mixinType))
                             {
                                 hasMixin = true;
                                 break;
                             }
                         }
                     }
                     if (!hasMixin)
                     {
                         throw new Exception(String.Format("The interceptor {0} is applied to the method {1} in the type {2} which does not have the mixin {3} that is required for the interceptor.",
                                                           interceptor.GetType().Name, baseMethod.Name, baseMethod.DeclaringType.Name, requiredMixinType.Name));
                     }
                 }
             }
         }
         else
         {
         }
     }
 }
示例#5
0
        /// <summary>
        /// 创建代理实例
        /// </summary>
        /// <param name="targetType">所要代理的接口类型</param>
        /// <param name="interceptor">拦截器</param>
        /// <returns>代理实例</returns>
        public static object Create(Type targetType, IInterceptor interceptor)
        {
            var interceptorType = interceptor.GetType();
            //声明一个返回值变量
            var variable            = Expression.Variable(targetType);
            var callexp             = Expression.Call(typeof(DispatchProxy), nameof(DispatchProxy.Create), new[] { targetType, typeof(ProxyGenerator) });
            var interceptorProperty = Expression.Property(Expression.Convert(variable, typeof(ProxyGenerator)), nameof(interceptor));
            var assign1             = Expression.Assign(variable, callexp);                                     //赋值操作
            var assign2             = Expression.Assign(interceptorProperty, Expression.Constant(interceptor)); //给接口赋值

            //构造代码块
            var block = Expression.Block(new[] { variable }, assign1, assign2, variable);

            return(Expression.Lambda <Func <object> >(block).Compile()());//建议缓存
        }
        public bool CanIntercept(Type type, MethodInfo methodInfo, IInterceptor interceptor)
        {
            List <Type> typesToExclude;

            if (!typeListToExcludePerInterceptor.TryGetValue(interceptor.GetType(), out typesToExclude))
            {
                return(true);
            }

            if (typesToExclude.Any(type.IsSubclassOf))
            {
                return(false);
            }

            return(true);
        }
示例#7
0
        private Boolean CanIntercept(MethodInfo methodInfo, IInterceptor interceptor)
        {
            List <String> regexForInterceptor;

            if (!RegexSelector.TryGetValue(interceptor.GetType(), out regexForInterceptor))
            {
                return(false);
            }
            if (regexForInterceptor == null)
            {
                return(false);
            }

            foreach (var regex in regexForInterceptor)
            {
                if (Regex.IsMatch(methodInfo.Name, regex))
                {
                    return(true);
                }
            }
            return(false);
        }
 public ObjectInterceptorCreator(IInterceptor interceptor,
                                 InterceptPredicate whitelists, InterceptPredicate blacklists) : base(interceptor.GetType(), whitelists, blacklists)
 {
     this.interceptor = interceptor;
 }
        public override Type Generate(IInterceptor interceptor, Type baseType, Type handlerType, params Type[] additionalInterfaceTypes)
        {
            var properties   = this.GetProperties(baseType, additionalInterfaceTypes);
            var methods      = this.GetMethods(baseType, additionalInterfaceTypes);
            var constructors = this.GetConstructors(baseType);

            var targetClass = new CodeTypeDeclaration(string.Concat(baseType.Name, "_Dynamic"));

            targetClass.IsClass        = baseType.IsClass;
            targetClass.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Serializable;
            targetClass.BaseTypes.Add((baseType.IsInterface == false) ? baseType : typeof(object));
            targetClass.BaseTypes.Add(proxyTypeReference.BaseType);

            foreach (var additionalInterfaceType in additionalInterfaceTypes)
            {
                targetClass.BaseTypes.Add(additionalInterfaceType);
            }

            var samples = new CodeNamespace(baseType.Namespace);

            samples.Imports.Add(new CodeNamespaceImport(typeof(string).Namespace));
            samples.Types.Add(targetClass);

            var targetUnit = new CodeCompileUnit();

            targetUnit.Namespaces.Add(samples);

            this.GenerateFields(targetClass, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null);

            this.GenerateConstructors(targetClass, baseType, constructors);

            this.GenerateMethods(targetClass, baseType, methods);

            this.GenerateProperties(targetClass, baseType, properties);

            var builder = new StringBuilder();

            using (var sourceWriter = new StringWriter(builder))
            {
                provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
            }

            var parameters = new CompilerParameters()
            {
                GenerateInMemory = true
            };

            this.AddReferences(parameters, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null, additionalInterfaceTypes);

            var results = provider.CompileAssemblyFromDom(parameters, targetUnit);

            if (results.Errors.HasErrors == true)
            {
                throw new InvalidOperationException(string.Join(Environment.NewLine, results.Errors.OfType <object>()));
            }

            return(results.CompiledAssembly.GetTypes().First());
        }
		public override Type Generate(IInterceptor interceptor, Type baseType, Type handlerType, params Type[] additionalInterfaceTypes)
		{
			var properties = this.GetProperties(baseType, additionalInterfaceTypes);
			var methods = this.GetMethods(baseType, additionalInterfaceTypes);
			var constructors = this.GetConstructors(baseType);

			var targetClass = new CodeTypeDeclaration(string.Concat(baseType.Name, "_Dynamic"));
			targetClass.IsClass = baseType.IsClass;
			targetClass.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Serializable;
			targetClass.BaseTypes.Add((baseType.IsInterface == false) ? baseType : typeof(object));
			targetClass.BaseTypes.Add(proxyTypeReference.BaseType);

			foreach (var additionalInterfaceType in additionalInterfaceTypes)
			{
				targetClass.BaseTypes.Add(additionalInterfaceType);
			}

			var samples = new CodeNamespace(baseType.Namespace);
			samples.Imports.Add(new CodeNamespaceImport(typeof(string).Namespace));
			samples.Types.Add(targetClass);

			var targetUnit = new CodeCompileUnit();
			targetUnit.Namespaces.Add(samples);

			this.GenerateFields(targetClass, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null);

			this.GenerateConstructors(targetClass, baseType, constructors);

			this.GenerateMethods(targetClass, baseType, methods);

			this.GenerateProperties(targetClass, baseType, properties);

			var builder = new StringBuilder();

			using (var sourceWriter = new StringWriter(builder))
			{
				provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
			}

			var parameters = new CompilerParameters() { GenerateInMemory = true };

			this.AddReferences(parameters, baseType, handlerType, (interceptor != null) ? interceptor.GetType() : null, additionalInterfaceTypes);

			var results = provider.CompileAssemblyFromDom(parameters, targetUnit);

			if (results.Errors.HasErrors == true)
			{
				throw new InvalidOperationException(string.Join(Environment.NewLine, results.Errors.OfType<object>()));
			}

			return (results.CompiledAssembly.GetTypes().First());
		}