Esempio n. 1
0
		public InvocationComposite(IMethodInterceptor[] interceptors,
								   Castle.Core.Interceptor.IInvocation innerInvocation, object[] arguments)
		{
			_interceptors = interceptors;
			_innerInvocation = innerInvocation;
			_arguments = arguments;
		}
Esempio n. 2
0
        public static object CreateWithInterceptor(Type serviceType, IMethodInterceptor methodInterceptor)
        {
            var proxy = Create(serviceType);

            ((InvokeProxy)(object)proxy).Initialize(serviceType, methodInterceptor);
            return(proxy);
        }
Esempio n. 3
0
        public void ValidInvocation()
        {        /*
                  *     Target target = new Target();
                  * MockRepository repository = new MockRepository();
                  * IMethodInterceptor interceptor = (IMethodInterceptor) repository.CreateMock(typeof (IMethodInterceptor));
                  * AbstractMethodInvocation join = CreateMethodInvocation(
                  * null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { interceptor });
                  * Expect.Call(interceptor.Invoke(join)).Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
                  * repository.ReplayAll();
                  * string score = (string) join.Proceed();
                  * Assert.AreEqual(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score);
                  * repository.VerifyAll();
                  */
            Target                   target = new Target();
            IMethodInterceptor       mock   = (IMethodInterceptor)mocks.CreateMock(typeof(IMethodInterceptor));
            AbstractMethodInvocation join   = CreateMethodInvocation(
                null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { mock });

            Expect.Call(mock.Invoke(null)).IgnoreArguments().Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
            mocks.ReplayAll();

            string score = (string)join.Proceed();

            Assert.AreEqual(Target.DefaultScore.ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score);

            mocks.VerifyAll();
        }
Esempio n. 4
0
        public override void Intercept(IMethodInterceptor interceptor)
        {
            var fieAssembly = LoadAssembly("FakeItEasy");
            if (fieAssembly == null) return;

            InterceptCallTo(interceptor, fieAssembly);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the list of
        /// <see langword="static"/> interceptors and dynamic interception
        /// advice that may apply to the supplied <paramref name="method"/>
        /// invocation.
        /// </summary>
        /// <param name="config">The proxy configuration.</param>
        /// <param name="proxy">The object proxy.</param>
        /// <param name="method">
        /// The method to evaluate interceptors for.
        /// </param>
        /// <param name="targetType">
        /// The <see cref="System.Type"/> of the target object.
        /// </param>
        /// <returns>
        /// A <see cref="System.Collections.IList"/> of
        /// <see cref="AopAlliance.Intercept.IMethodInterceptor"/> (if there's
        /// a dynamic method matcher that needs evaluation at runtime).
        /// </returns>
        public static IList <object> CalculateInterceptors(
            IAdvised config, object proxy, MethodInfo method, Type targetType)
        {
            IList <object> interceptors = new List <object>(config.Advisors.Count);

            foreach (IAdvisor advisor in config.Advisors)
            {
                if (advisor is IPointcutAdvisor)
                {
                    IPointcutAdvisor pointcutAdvisor = (IPointcutAdvisor)advisor;
                    if (pointcutAdvisor.Pointcut.TypeFilter.Matches(targetType))
                    {
                        IMethodInterceptor interceptor =
                            (IMethodInterceptor)GlobalAdvisorAdapterRegistry.Instance.GetInterceptor(advisor);
                        IMethodMatcher mm = pointcutAdvisor.Pointcut.MethodMatcher;
                        if (mm.Matches(method, targetType))
                        {
                            if (mm.IsRuntime)
                            {
                                // Creating a new object instance in the GetInterceptor() method
                                // isn't a problem as we normally cache created chains...
                                interceptors.Add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
                            }
                            else
                            {
                                interceptors.Add(interceptor);
                            }
                        }
                    }
                }
            }
            return(interceptors);
        }
        public void InterceptMethod(IMethodInterceptor methodInterceptor)
        {
            // Perform logging here, e.g.:
            string args = string.Join(", ",
                methodInterceptor.InputParameters.Select(x => (x ?? string.Empty).ToString()));
            Trace.WriteLine(string.Format("Mugen: {0}({1})", methodInterceptor.Member.Name, args));

            methodInterceptor.ProcessInTarget();
        }
Esempio n. 7
0
        public void InterceptMethod(IMethodInterceptor methodInterceptor)
        {
            // Perform logging here, e.g.:
            string args = string.Join(", ",
                                      methodInterceptor.InputParameters.Select(x => (x ?? string.Empty).ToString()));

            Trace.WriteLine(string.Format("Mugen: {0}({1})", methodInterceptor.Member.Name, args));

            methodInterceptor.ProcessInTarget();
        }
Esempio n. 8
0
 public static TInterface CreateAopProxy <TInterface>(TInterface origin, IMethodInterceptor methodInterceptor, IAroundInterceptor aroundInterceptor)
 {
     lock (DynamicProxyFactory.AopProxyEmitter)
     {
         Type orignType   = typeof(TInterface);
         Type dynamicType = DynamicProxyFactory.AopProxyEmitter.EmitProxyType <TInterface>(orignType);
         //DynamicProxyFactory.AopProxyEmitter.Save();
         ConstructorInfo ctor = dynamicType.GetConstructor(new Type[] { orignType, typeof(IMethodInterceptor), typeof(IAroundInterceptor) });
         return((TInterface)ctor.Invoke(new object[] { origin, methodInterceptor, aroundInterceptor }));
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Add a service proxied and advised using the appropriate around AOP advice
        /// </summary>
        public static void AddAdvisedService <IServiceInterface>(IServiceInterface implementation,
                                                                 IMethodInterceptor interceptor)
        {
            CreateServicesTable();
            ProxyFactory proxyFactory = new ProxyFactory(implementation);

            proxyFactory.AddAdvice(interceptor);
            IServiceInterface service = (IServiceInterface)proxyFactory.GetProxy();

            _services.Add(typeof(IServiceInterface), service);
        }
Esempio n. 10
0
 public static object CreateAopProxy(Type proxyIntfaceType, object origin, IMethodInterceptor methodInterceptor, IAroundInterceptor aroundInterceptor)
 {
     lock (DynamicProxyFactory.AopProxyEmitter)
     {
         Type orignType   = origin.GetType();
         Type dynamicType = DynamicProxyFactory.AopProxyEmitter.EmitProxyType(proxyIntfaceType, orignType);
         //DynamicProxyFactory.AopProxyEmitter.Save();
         ConstructorInfo ctor = dynamicType.GetConstructor(new Type[] { orignType, typeof(IMethodInterceptor), typeof(IAroundInterceptor) });
         return(ctor.Invoke(new object[] { origin, methodInterceptor, aroundInterceptor }));
     }
 }
Esempio n. 11
0
        private static void InterceptCallTo(IMethodInterceptor interceptor, Assembly assembly)
        {
            var aType = assembly.GetType("FakeItEasy.A");

            var callToOfTFunc = GetCallToOfT(aType, typeof(Func<>));
            var callToOfTAction = GetCallToOfT(aType, typeof(Action));

            interceptor.InterceptMethod(callToOfTFunc);
            interceptor.InterceptMethod(callToOfTAction);

            Cop.Intercept();
        }
Esempio n. 12
0
        public void UnwrapsTargetInvocationException_WithInterceptorThatThrowsAnException()
        {
            BadCommand               target = new BadCommand();
            IMethodInterceptor       mock   = A.Fake <IMethodInterceptor>();
            AbstractMethodInvocation join   = CreateMethodInvocation(
                null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock });

            A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Throws <NotImplementedException>();

            // we want this exception to bubble up...
            Assert.Throws <NotImplementedException>(() => join.Proceed());
        }
Esempio n. 13
0
        public object CreateProxy(
            Type instanceType,
            IMethodInterceptor interceptor,
            params Type[] baseInterfaces)
        {
            Type   proxyType = CreateProxyType(instanceType, baseInterfaces);
            object result    = Activator.CreateInstance(proxyType);
            IProxy proxy     = (IProxy)result;

            proxy.Interceptor = interceptor;

            return(result);
        }
Esempio n. 14
0
        public T CreateProxy <T>(
            IMethodInterceptor interceptor,
            params Type[] baseInterfaces)
        {
            Type proxyType = CreateProxyType(typeof(T), baseInterfaces);
            T    result    = (T)Activator.CreateInstance(proxyType);

            IProxy proxy = (IProxy)result;

            proxy.Interceptor = interceptor;

            return(result);
        }
        private static void InterceptCallTo(IMethodInterceptor interceptor, Assembly assembly)
        {
            var aType = assembly.GetType("FakeItEasy.A");

            var unboundExpression = typeof (Expression<>);
            var unboundFunc = typeof (Func<>);
            var boundExprOfFunc = unboundExpression.MakeGenericType(unboundFunc);

            var callToOfT = aType.GetGenericMethod("CallTo", new[] {boundExprOfFunc});

            interceptor.InterceptMethod(callToOfT);

            Cop.Intercept();
        }
Esempio n. 16
0
        protected IMethodInterceptor[] ObtainInterceptors(IKernel kernel, ComponentModel model)
        {
            IMethodInterceptor[] interceptors = new IMethodInterceptor[model.Interceptors.Count];
            int index = 0;

            foreach (InterceptorReference interceptorRef in model.Interceptors)
            {
                IHandler handler = null;

                if (interceptorRef.ReferenceType == InterceptorReferenceType.Interface)
                {
                    handler = kernel.GetHandler(interceptorRef.ServiceType);
                }
                else
                {
                    handler = kernel.GetHandler(interceptorRef.ComponentKey);
                }

                if (handler == null)
                {
                    // This shoul be virtually impossible to happen
                    // Seriously!
                    throw new ApplicationException("The interceptor could not be resolved");
                }

                try
                {
                    IMethodInterceptor interceptor = (IMethodInterceptor)handler.Resolve();

                    interceptors[index++] = interceptor;

                    SetOnBehalfAware(interceptor as IOnBehalfAware, model);
                }
                catch (InvalidCastException)
                {
                    String message = String.Format(
                        "An interceptor registered for {0} doesnt implement " +
                        "the IMethodInterceptor interface",
                        model.Name);

                    throw new ApplicationException(message);
                }
            }

            return(interceptors);
        }
Esempio n. 17
0
        /// <summary>
        /// 获取指定类型的动态代理
        /// </summary>
        /// <param name="genericType"></param>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        private object GetProxyService(Type genericType, Type serviceType)
        {
            object result    = null;
            Type   proxyType = null;
            object proxy     = null;

            if (genericType == typeof(IInvocation <>))
            {
                proxyType = serviceType.GetGenericArguments()[0];
                proxy     = DynamicProxy.Create(proxyType);
                result    = InvocationProxyFactory.CreateInvocation(proxyType, proxy);
            }
            else if (genericType == typeof(IInvocation <,>))
            {
                proxyType = serviceType.GetGenericArguments()[0];
                var interceptorType = serviceType.GetGenericArguments()[1];
                IMethodInterceptor methodInterceptor = (IMethodInterceptor)
                                                       _serviceProvider.GetRequiredService(interceptorType);

                proxy  = DynamicProxy.CreateWithInterceptor(proxyType, methodInterceptor);
                result = InvocationProxyFactory.CreateInvocationWithInterceptor(proxyType, proxy, methodInterceptor);
            }
            return(result);
        }
Esempio n. 18
0
        public void UnwrapsTargetInvocationException_WithInterceptorThatThrowsAnException()
        {
            BadCommand               target = new BadCommand();
            IMethodInterceptor       mock   = (IMethodInterceptor)mocks.CreateMock(typeof(IMethodInterceptor));
            AbstractMethodInvocation join   = CreateMethodInvocation(
                null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock });

            Expect.Call(mock.Invoke(null)).IgnoreArguments().Throw(new NotImplementedException());
            mocks.ReplayAll();

            try
            {
                join.Proceed();
            }
            catch (NotImplementedException)
            {
                // this is good, we want this exception to bubble up...
            }
            catch (TargetInvocationException)
            {
                Assert.Fail("Must have unwrapped this.");
            }
            mocks.VerifyAll();
        }
Esempio n. 19
0
		private void InitializeInterceptor(IMethodInterceptor interceptor)
		{
//			if (interceptor is IAspectEngineAware)
//			{
//				(interceptor as IAspectEngineAware).SetEngine(_engine);
//			}
		}
Esempio n. 20
0
		protected IMethodInterceptor[] CreateInterceptor(InterceptorDefinitionCollection advices)
		{
			IMethodInterceptor[] interceptors = new IMethodInterceptor[advices.Count];

			for (int i = 0; i < interceptors.Length; i++)
			{
				Type adviceType = advices[i].TypeReference.ResolvedType;
				interceptors[i] = ObtainInterceptorInstance(adviceType);
			}

			return interceptors;
		}
Esempio n. 21
0
		protected void RegisterInCache(MethodInfo method, IMethodInterceptor[] interceptors)
		{
			_method2Advices[method] = interceptors;
		}
Esempio n. 22
0
 internal void Initialize(Type serviceType, IMethodInterceptor interceptor)
 {
     _serviceType = serviceType;
     Interceptors.Add(interceptor);
 }
Esempio n. 23
0
        /// <summary>
        /// Initializes the members which will have been and will be referenced.
        /// </summary>
        private void InitializeReferencedMembers()
        {
            // interfaces
            IInjectAfterInitializer  = ResolveType("IInjectAfterInitializer");
            IInjectBeforeInitializer = ResolveType("IInjectBeforeInitializer");
            IInstanceAware           = ResolveType("IInstanceAware");
            IMemberAware             = ResolveType("IMemberAware");
            IMethodInterceptor       = ResolveType("IMethodInterceptor");
            IMethodReturnInterceptor = ResolveType("IMethodReturnInterceptor");
            IParameterInterceptor    = ResolveType("IParameterInterceptor");
            IPropertyGetInterceptor  = ResolveType("IPropertyGetInterceptor");
            IPropertySetInterceptor  = ResolveType("IPropertySetInterceptor");
            IRequireInitialization   = ResolveType("IRequireInitialization");

            // classes
            CompilationImplementsAttribute = ResolveType("CompilationImplementsAttribute");
            CompilationOptionsAttribute    = ResolveType("CompilationOptionsAttribute");
            Exception                    = ResolveType("Exception");
            MethodBase                   = ResolveType("MethodBase");
            MethodInfo                   = ResolveType("MethodInfo");
            MethodInterceptionArgs       = ResolveType("MethodInterceptionArgs");
            MethodReturnInterceptionArgs = ResolveType("MethodReturnInterceptionArgs");
            ObjectArray                  = new ArrayType(ResolveType("Object"));
            ParameterInfo                = ResolveType("ParameterInfo");
            ParameterInterceptionArgs    = ResolveType("ParameterInterceptionArgs");
            PropertyInfo                 = ResolveType("PropertyInfo");
            PropertyInterceptionArgs     = ResolveType("PropertyInterceptionArgs");
            Type      = ResolveType("Type");
            TypeArray = new ArrayType(Type);

            // constructors
            CompilerGeneratedAttributeCtor   = ResolveType("CompilerGeneratedAttribute").GetConstructor();
            MethodInterceptionArgsCtor       = MethodInterceptionArgs.GetConstructor();
            MethodReturnInterceptionArgsCtor = MethodReturnInterceptionArgs.GetConstructor();
            NonSerializedAttributeCtor       = ResolveType("NonSerializedAttribute").GetConstructor();
            ParameterInterceptionArgsCtor    = ParameterInterceptionArgs.GetConstructor();
            PropertyInterceptionArgsCtor     = PropertyInterceptionArgs.GetConstructor();

            // methods
            MethodBaseGetMethodFromHandle        = ResolveType("MethodBase").GetMethod("GetMethodFromHandle", parameters: new[] { ResolveType("RuntimeMethodHandle") });
            MethodBaseGetMethodFromHandleAndType = ResolveType("MethodBase").GetMethod("GetMethodFromHandle", parameters: new[] { ResolveType("RuntimeMethodHandle"), ResolveType("RuntimeTypeHandle") });
            MethodBaseGetParameters         = ResolveType("MethodBase").GetMethod("GetParameters");
            MethodInterceptorOnEnter        = IMethodInterceptor.GetMethod("OnEnter");
            MethodInterceptorOnException    = IMethodInterceptor.GetMethod("OnException");
            MethodInterceptorOnExit         = IMethodInterceptor.GetMethod("OnExit");
            MethodReturnInterceptorOnReturn = IMethodReturnInterceptor.GetMethod("OnReturn");
            ParameterInterceptorOnEnter     = IParameterInterceptor.GetMethod("OnEnter");
            PropertyGetInterceptorOnExit    = IPropertyGetInterceptor.GetMethod("OnExit");
            PropertyGetInterceptorOnGet     = IPropertyGetInterceptor.GetMethod("OnGet");
            PropertySetInterceptorOnExit    = IPropertySetInterceptor.GetMethod("OnExit");
            PropertySetInterceptorOnSet     = IPropertySetInterceptor.GetMethod("OnSet");
            RequireInitializationInitialize = IRequireInitialization.GetMethod("Initialize");
            TypeGetProperty       = Type.GetMethod("GetProperty", parameters: new[] { ResolveType("String"), ResolveType("BindingFlags") });
            TypeGetTypeFromHandle = Type.GetMethod("GetTypeFromHandle", parameters: new[] { ResolveType("RuntimeTypeHandle") });
            TypeMakeGenericType   = Type.GetMethod("MakeGenericType");

            // properties

            InstanceAwareInstanceSet             = IInstanceAware.GetProperty("Instance").Resolve().SetMethod.Import();
            MemberAwareMemberSet                 = IMemberAware.GetProperty("Member").Resolve().SetMethod.Import();
            MethodInterceptionArgsCancelGet      = MethodInterceptionArgs.GetProperty("Cancel").Resolve().GetMethod.Import();
            MethodInterceptionArgsReturnGet      = MethodInterceptionArgs.GetProperty("Return").Resolve().GetMethod.Import();
            MethodInterceptionArgsReturnSet      = MethodInterceptionArgs.GetProperty("Return").Resolve().SetMethod.Import();
            MethodReturnInterceptionArgsValueGet = MethodReturnInterceptionArgs.GetProperty("Value").Resolve().GetMethod.Import();
            MethodReturnInterceptionArgsValueSet = MethodReturnInterceptionArgs.GetProperty("Value").Resolve().SetMethod.Import();
            ParameterInterceptionArgsValueGet    = ParameterInterceptionArgs.GetProperty("Value").Resolve().GetMethod.Import();
            PropertyInterceptionArgsIsDirtyGet   = PropertyInterceptionArgs.GetProperty("IsDirty").Resolve().GetMethod.Import();
            PropertyInterceptionArgsValueGet     = PropertyInterceptionArgs.GetProperty("Value").Resolve().GetMethod.Import();
            PropertyInterceptionArgsValueSet     = PropertyInterceptionArgs.GetProperty("Value").Resolve().SetMethod.Import();
            TypeTypeHandleGet = Type.GetProperty("TypeHandle").Resolve().GetMethod.Import();
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes the new instance of  <see cref="ProxyGenerator"/> class.
 /// </summary>
 /// <param name="interceptor">Target method interceptor to invoke.</param>
 public ProxyGenerator(IMethodInterceptor interceptor)
 {
     this.interceptor = interceptor;
 }
Esempio n. 25
0
		private IMethodInterceptor[] ObtainAdvicesForMethod(MethodInfo method, object instance, object[] arguments)
		{
			IMethodInterceptor[] interceptors = ObtainFromCache(method);

			if (interceptors == null)
			{
				PointCutDefinition[] pointcuts = _matcher.Match(method);

				if (pointcuts.Length != 0)
				{
					interceptors = ObtainAdvices(pointcuts);
				}
				else
				{
					interceptors = new IMethodInterceptor[0];
					;
				}

				RegisterInCache(method, interceptors);
			}

			return interceptors;
		}
Esempio n. 26
0
 public void SetUp()
 {
     _oneWayInterceptor = MockRepository.GenerateMock <IMethodInterceptor>();
     _twoWayInterceptor = MockRepository.GenerateMock <IMethodInterceptor>();
 }
Esempio n. 27
0
        public static object CreateInvocationWithInterceptor(Type serviceType, object target, IMethodInterceptor interceptor)
        {
            Type invocationType = typeof(InvocationProxy <,>);

            Type[] genericTypeArgs       = { serviceType, interceptor.GetType() };
            var    invocationGenericType = invocationType.MakeGenericType(genericTypeArgs);
            object result = Activator.CreateInstance(invocationGenericType, target, interceptor);

            return(result);
        }
 public ProxiedMethodInterceptor(IMethodInterceptor interceptor)
 {
     this.interceptor = interceptor;
 }
 public InterceptorAndDynamicMethodMatcher(IMethodInterceptor interceptor, IMethodMatcher methodMatcher)
 {
     this.Interceptor   = interceptor;
     this.MethodMatcher = methodMatcher;
 }
		public InterceptorAndDynamicMethodMatcher(IMethodInterceptor interceptor, IMethodMatcher methodMatcher)
		{
			this.Interceptor = interceptor;
			this.MethodMatcher = methodMatcher;
		}
Esempio n. 31
0
 public abstract void Intercept(IMethodInterceptor interceptor);
 public RemoteCallInterceptor(IMethodInterceptor oneWayInterceptor, IMethodInterceptor twoWayInterceptor, RemoteExecutionPolicies policies)
 {
     _oneWayInterceptor = oneWayInterceptor;
     _twoWayInterceptor = twoWayInterceptor;
     _policies          = policies;
 }