protected virtual void ApplyCommissionConcerns(object instance)
        {
            if (Model.Lifecycle.HasCommissionConcerns == false)
            {
                return;
            }

            instance = ProxyUtil.GetUnproxiedInstance(instance);
            if (instance == null)
            {
                // see http://issues.castleproject.org/issue/IOC-332 for details
                throw new NotSupportedException(string.Format("Can not apply commission concerns to component {0} because it appears to be a target-less proxy. Currently those are not supported.", Model.Name));
            }
            ApplyConcerns(Model.Lifecycle.CommissionConcerns, instance);
        }
        public void ProxyGenerator_CreateInterfaceProxyWithoutTarget_cannot_proceed_to_delegate_type_mixin()
        {
            var options = new ProxyGenerationOptions();

            options.AddDelegateTypeMixin(typeof(Action));

            var interceptor = new Interceptor(shouldProceed: true);

            var proxy  = generator.CreateInterfaceProxyWithoutTarget(typeof(IComparable), options, interceptor);
            var action = ProxyUtil.CreateDelegateToMixin <Action>(proxy);

            Assert.NotNull(action);

            Assert.Throws <NotImplementedException>(() => action.Invoke());
        }
        protected void GenerateConstructors(ClassEmitter emitter, Type baseType, params FieldReference[] fields)
        {
            var constructors =
                baseType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var constructor in constructors)
            {
                if (!ProxyUtil.IsAccessibleMethod(constructor))
                {
                    continue;
                }

                GenerateConstructor(emitter, constructor, fields);
            }
        }
        /// <summary>
        /// 执行自动注册
        /// </summary>
        /// <param name="context"></param>
        public void Start(IComponentContext context)
        {
            lock (this)
            {
                context.TryResolve <AutoConfigurationList>(out var autoConfigurationList);
                if (autoConfigurationList == null || autoConfigurationList.AutoConfigurationDetailList == null || !autoConfigurationList.AutoConfigurationDetailList.Any())
                {
                    return;
                }
                foreach (var autoConfigurationDetail in autoConfigurationList.AutoConfigurationDetailList)
                {
                    context.TryResolve(autoConfigurationDetail.AutoConfigurationClassType, out var autoConfigurationInstance);
                    if (autoConfigurationInstance == null)
                    {
                        continue;
                    }


                    foreach (var beanMethod in autoConfigurationDetail.BeanMethodInfoList)
                    {
                        if (beanMethod.Item2.IsVirtual)
                        {
                            throw new InvalidOperationException(
                                      $"The Configuration class `{autoConfigurationDetail.AutoConfigurationClassType.FullName}` method `{beanMethod.Item2.Name}` can not be virtual!");
                        }

                        if (!ProxyUtil.IsAccessible(beanMethod.Item2.ReturnType))
                        {
                            throw new InvalidOperationException(
                                      $"The Configuration class `{autoConfigurationDetail.AutoConfigurationClassType.FullName}` method `{beanMethod.Item2.Name}` returnType is not accessible!");
                        }
                        if (beanMethod.Item2.ReturnType.IsValueType || beanMethod.Item2.ReturnType.IsEnum)
                        {
                            throw new InvalidOperationException(
                                      $"The Configuration class `{autoConfigurationDetail.AutoConfigurationClassType.FullName}` method `{beanMethod.Item2.Name}` returnType is invalid!");
                        }

                        var result = AutoConfigurationHelper.InvokeInstanceMethod(context, autoConfigurationDetail, autoConfigurationInstance, beanMethod.Item2);
                        if (result == null)
                        {
                            continue;
                        }
                        AutoConfigurationHelper.RegisterInstance(context.ComponentRegistry, beanMethod.Item2.ReturnType,
                                                                 result, beanMethod.Item1.Key).CreateRegistration();
                    }
                }
            }
        }
Exemple #5
0
        public void ProxyGenerator_CreateClassProxy_can_create_callable_delegate_proxy_without_target()
        {
            var options = new ProxyGenerationOptions();

            options.AddDelegateTypeMixin(typeof(Action));

            var interceptor = new Interceptor();

            var proxy  = generator.CreateClassProxy(typeof(object), options, interceptor);
            var action = ProxyUtil.CreateDelegateToMixin <Action>(proxy);

            Assert.NotNull(action);

            action.Invoke();
            Assert.AreSame(typeof(Action).GetMethod("Invoke"), interceptor.LastInvocation.Method);
        }
Exemple #6
0
        private static K9AbpRepositoryBase <TEntity, TPrimaryKey> GetUnproxiedType <TEntity, TPrimaryKey>(
            this IRepository <TEntity, TPrimaryKey> repository)
            where TEntity : class, IEntity <TPrimaryKey>
        {
            if (repository is K9AbpRepositoryBase <TEntity, TPrimaryKey> repositoryBase)
            {
                return(repositoryBase);
            }
            var result = ProxyUtil.GetUnproxiedInstance(repository) as K9AbpRepositoryBase <TEntity, TPrimaryKey>;

            if (result != null)
            {
                return(result);
            }
            throw new NotSupportedException();
        }
Exemple #7
0
        public void AddTypedFactoryEntry(FactoryEntry entry)
        {
            var model = new ComponentModel(new ComponentName(entry.Id, true), new[] { entry.FactoryInterface }, typeof(Empty),
                                           new Arguments().Insert("typed.fac.entry", entry))
            {
                LifestyleType = LifestyleType.Singleton
            };

            model.Interceptors.Add(new InterceptorReference(typeof(FactoryInterceptor)));

            var proxyOptions = ProxyUtil.ObtainProxyOptions(model, true);

            proxyOptions.OmitTarget = true;

            ((IKernelInternal)Kernel).AddCustomComponent(model);
        }
 private bool ShouldCreateProxy(object instance)
 {
     if (instance == null)
     {
         return false;
     }
     if (Kernel.ProxyFactory.ShouldCreateProxy(Model) == false)
     {
         return false;
     }
     if (ProxyUtil.IsProxy(instance))
     {
         return false;
     }
     return true;
 }
Exemple #9
0
        internal static object UnwrapProxy(object proxy)
        {
            if (!ProxyUtil.IsProxy(proxy))
            {
                return(proxy);
            }

            try
            {
                return(ProxyUtil.GetUnproxiedInstance(proxy));
            }
            catch (Exception)
            {
                return(proxy);
            }
        }
            public void GivenBuiltProxyWithTargetAndMixin_WhenMemberIsCalled_ThenMixinMemberIsIntercepted()
            {
                var subjectBuilder = new DynamicProxyBuilder();

                // Given
                var aTarget = new ClassA();

                aTarget.AP1 = "val1";
                var aInterceptor = new InterceptorA();
                var abMixin      = new MixinAB(mixinAProperty: 2)
                {
                    MixinBProperty = 3
                };
                var proxy = subjectBuilder
                            .ForClass <ClassA>()
                            .WithTarget(aTarget)
                            .AddInterceptor(aInterceptor)
                            .WithMixin(abMixin)
                            .Build();

                // When
                int aValue = 0;

                proxy.AMethod(() => aValue += 5);
                (proxy as IMixinA).MixinAMethod(() => aValue += 5);
                (proxy as IMixinB).MixinBMethod(() => aValue += 5);

                var ret1_AP1            = proxy.AP1;
                var ret1_MixinAProperty = (proxy as IMixinA).MixinAProperty;
                var ret1_MixinBProperty = (proxy as IMixinB).MixinBProperty;

                proxy.AP1 = "val2";
                (proxy as IMixinB).MixinBProperty = 4;
                var ret2_AP1            = proxy.AP1;
                var ret2_MixinBProperty = (proxy as IMixinB).MixinBProperty;


                // Then
                Assert.IsTrue(ProxyUtil.IsProxy(proxy), "object is not a proxy");
                Assert.AreEqual(10, aInterceptor.InterceptReceivedCall);
                Assert.AreEqual(15, aValue);
                Assert.AreEqual("val1", ret1_AP1);
                Assert.AreEqual("val2", ret2_AP1);
                Assert.AreEqual(2, ret1_MixinAProperty);
                Assert.AreEqual(3, ret1_MixinBProperty);
                Assert.AreEqual(4, ret2_MixinBProperty);
            }
Exemple #11
0
        internal static TType UnwrapProxy <TType>(TType proxy)
        {
            if (!ProxyUtil.IsProxy(proxy))
            {
                return(proxy);
            }

            try
            {
                dynamic dynamicProxy = proxy;
                return(dynamicProxy.__target);
            }
            catch (RuntimeBinderException)
            {
                return(proxy);
            }
        }
        protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone)
        {
            if (ProxyUtil.IsAccessibleMethod(method) == false)
            {
                return(null);
            }

            var accepted = AcceptMethod(method, true, hook);

            if (!accepted && !method.IsAbstract)
            {
                //we don't need to do anything...
                return(null);
            }

            return(new MetaMethod(method, method, isStandalone, accepted, hasTarget: true));
        }
Exemple #13
0
            public void GivenBuiltProxyWithTwoMixins_WhenMemberIsCalled_ThenMixinMembersAreIntecepted()
            {
                var subjectBuilder = new DynamicProxyBuilder();

                // Given
                var aInterceptor = new InterceptorA();
                var aMixin       = new MixinA(mixinAProperty: 4);
                var bMixin       = new MixinB();
                var proxy        = subjectBuilder
                                   .ForClass <ClassA>()
                                   .WithoutTraget()
                                   .AddInterceptor(aInterceptor)
                                   .WithMixin(aMixin)
                                   .WithMixin(bMixin)
                                   .Build();

                // When
                int aValue = 0;

                proxy.AMethod(() => aValue += 2); // i1
                proxy.AP1 = "a1";                 // i2
                proxy.AP2 = new ClassB {
                    P1 = 11, P2 = "22"
                };                                                  // i3
                (proxy as IMixinA).MixinAMethod(() => aValue += 4); // i4
                (proxy as IMixinB).MixinBMethod(() => aValue += 8); // i5
                (proxy as IMixinB).MixinBProperty             = 33; // i6

                var retAP1            = proxy.AP1;                  // i7
                var retAP2            = proxy.AP2;                  // i8
                var retAP2_P1         = retAP2.P1;
                var retAP2_P2         = retAP2.P2;
                var retAP2_PowerTwo   = proxy.AP2.PowerTwo(4);             // i9
                var retMixinAProperty = (proxy as IMixinA).MixinAProperty; // i10
                var retMixinBProperty = (proxy as IMixinB).MixinBProperty; // i11

                // Then
                Assert.IsTrue(ProxyUtil.IsProxy(proxy), "object is not a proxy");
                Assert.AreEqual(11, aInterceptor.InterceptReceivedCall);
                Assert.AreEqual("a1", retAP1);
                Assert.AreEqual(11, retAP2_P1);
                Assert.AreEqual("22", retAP2_P2);
                Assert.AreEqual(16, retAP2_PowerTwo);
                Assert.AreEqual(4, retMixinAProperty);
                Assert.AreEqual(33, retMixinBProperty);
            }
        public Task <TResponse> Handle(TRequest request)
        {
            var index = -1;
            Func <TRequest, Task <TResponse> > next = null;

            next = req =>
            {
                ++index;
                return(index < _middleware.Length
                     ? _middleware[index].Apply(request, next)
                     : _inner.Handle(request));
            };

            Env.Use(new PipelineContext(ProxyUtil.GetUnproxiedType(_inner)));

            return(next(request));
        }
Exemple #15
0
        public static void Demo()
        {
            // Adding interception to an interface proxy.  Invoke() is hosted on a target class that is not inherited from
            var incSub = new IncumbentSubclass();

            incSub.Init("World!");
            var proxyGenerator = new ProxyGenerator();
            var altHello       = proxyGenerator.CreateInterfaceProxyWithTarget <IHello>(incSub, new MyInterceptor());

            // var altHello = proxyGenerator.CreateClassProxy<IncumbentSubclass>(cls, );
            Debug.Assert(altHello.Hello() == "World!");
            // Debug.Assert(((Incumbent)altHello).StuckWithThis() == "blah");  NOPE
            Debug.Assert(((Incumbent)ProxyUtil.GetUnproxiedInstance(altHello)).StuckWithThis() == "blah");

            // ProxyUtil.CreateDelegateToMixin<>()  Does not appear useful... an interface facet to a given object with Invoke()

            // Resulting proxy impl of an interface inherits from a given parent class... but cannot seem to initialize ?!
            // Actually... this is bugged.  Need 'WithoutTarget'
            var options = new ProxyGenerationOptions
            {
                BaseTypeForInterfaceProxy = typeof(IncumbentSubclass)
            };

            altHello = proxyGenerator.CreateInterfaceProxyWithTarget <IHello>(incSub, options, new MyInterceptor());
            incSub   = (IncumbentSubclass)altHello;
            incSub.Init("Bingo!");
            var helloResponse = altHello.Hello();

            // Debug.Assert(helloResponse == "Bingo!"); // why not?
            Debug.Assert(helloResponse == "World!"); // WHY?

            // completely skip target class !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            options = new ProxyGenerationOptions
            {
                BaseTypeForInterfaceProxy = typeof(Incumbent)
            };
            altHello = proxyGenerator.CreateInterfaceProxyWithoutTarget <IHello>(options, new MyMetaImpl("Yellow!"));
            Debug.Assert(((Incumbent)altHello).StuckWithThis() == "blah");
            Debug.Assert(altHello.Hello() == "Yellow!");

            // Hmmm.... this isn't going to work.  Seems like we need a no-arg constructor in proxy parent class.
            var incSub2 = new IncumbentSubclass2("this'll be interesting");

            proxyGenerator.CreateInterfaceProxyWithTarget(typeof(IHello), incSub2, new MyMetaImpl("Dolly!"));
        }
Exemple #16
0
        private MethodAttributes ObtainAttributes()
        {
            var methodInfo = Method;
            var attributes = MethodAttributes.Virtual;

            if (methodInfo.IsFinal || Method.DeclaringType.IsInterface)
            {
                attributes |= MethodAttributes.NewSlot;
            }

            if (methodInfo.IsPublic)
            {
                attributes |= MethodAttributes.Public;
            }

            if (methodInfo.IsHideBySig)
            {
                attributes |= MethodAttributes.HideBySig;
            }
            if (
                ProxyUtil.IsInternal(methodInfo) &&
                ProxyUtil.AreInternalsVisibleToDynamicProxy(methodInfo.DeclaringType.Assembly)
                )
            {
                attributes |= MethodAttributes.Assembly;
            }
            if (methodInfo.IsFamilyAndAssembly)
            {
                attributes |= MethodAttributes.FamANDAssem;
            }
            else if (methodInfo.IsFamilyOrAssembly)
            {
                attributes |= MethodAttributes.FamORAssem;
            }
            else if (methodInfo.IsFamily)
            {
                attributes |= MethodAttributes.Family;
            }

            if (Standalone == false)
            {
                attributes |= MethodAttributes.SpecialName;
            }
            return(attributes);
        }
Exemple #17
0
 public void DynamicProxyWithoutInterfaceTest()
 {
     try
     {
         var demo = _container.Resolve <DemoClassWithoutInterface>();
         Assert.Empty(LoggingInterceptor.Calls);
         demo.HelloWorld();
         Assert.Single(LoggingInterceptor.Calls);
         Assert.Equal(nameof(DemoClassWithoutInterface.HelloWorld), LoggingInterceptor.Calls.Single());
         var type = demo.GetType();
         Assert.NotEqual(typeof(DemoClassWithoutInterface), type);
         Assert.Equal(typeof(DemoClassWithoutInterface), ProxyUtil.GetUnproxiedType(demo));
     }
     finally
     {
         LoggingInterceptor.Calls.Clear();
     }
 }
Exemple #18
0
        public void ProxyGenerator_CreateInterfaceProxyWithTarget_can_proceed_to_delegate_mixin()
        {
            var target = new Target();

            var options = new ProxyGenerationOptions();

            options.AddDelegateMixin(new Action(target.Method));

            var interceptor = new Interceptor(shouldProceed: true);

            var proxy  = generator.CreateInterfaceProxyWithTarget(typeof(IComparable), target, options, interceptor);
            var action = ProxyUtil.CreateDelegateToMixin <Action>(proxy);

            Assert.NotNull(action);

            action.Invoke();
            Assert.True(target.MethodInvoked);
        }
        public void ServiceProxyTest()
        {
            var service = ServiceProvider.GetService <IFooService>();

            var isProxy = ProxyUtil.IsProxy(service);

            Assert.True(isProxy);

            var executeResult = service.Execute();

            Assert.Equal("Foo-Bar", executeResult);

            var service2 = ServiceProvider.GetService <IFooService>();

            var equalsResult = ReferenceEquals(service, service2);

            Assert.False(equalsResult);
        }
Exemple #20
0
 private static void EnsureInterfaceInterceptionApplies(IComponentRegistration componentRegistration)
 {
     if (componentRegistration.Services
         .OfType <IServiceWithType>()
         .Select(s => new Tuple <Type, TypeInfo>(s.ServiceType, s.ServiceType.GetTypeInfo()))
         .Any(s => !s.Item2.IsInterface || !ProxyUtil.IsAccessible(s.Item1)))
     {
         //throw new InvalidOperationException(
         //    string.Format(
         //        CultureInfo.CurrentCulture,
         //        RegistrationExtensionsResources.InterfaceProxyingOnlySupportsInterfaceServices,
         //        componentRegistration));
         throw new InvalidOperationException(
                   string.Format(
                       "The component {0} cannot use interface interception as it provides services that are not publicly visible interfaces. Check your registration of the component to ensure you're not enabling interception and registering it as an internal/private interface type.",
                       componentRegistration));
     }
 }
Exemple #21
0
        protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone)
        {
            if (ProxyUtil.IsAccessibleMethod(method) == false)
            {
                return(null);
            }

            if (onlyProxyVirtual && IsVirtuallyImplementedInterfaceMethod(method))
            {
                return(null);
            }

            var methodOnTarget = GetMethodOnTarget(method);

            var proxyable = AcceptMethod(method, onlyProxyVirtual, hook);

            return(new MetaMethod(method, methodOnTarget, isStandalone, proxyable, methodOnTarget.IsPrivate == false));
        }
Exemple #22
0
        public void RegisterFacility_WithControlProxyHook_WorksFine()
        {
            var type       = typeof(SynchronizeFacility).FullName;
            var container2 = new WindsorContainer();
            var facNode    = new MutableConfiguration("facility");

            facNode.Attributes["type"] = type;
            facNode.Attributes[Constants.ControlProxyHookAttrib] = typeof(DummyProxyHook).AssemblyQualifiedName;
            container2.Kernel.ConfigurationStore.AddFacilityConfiguration(type, facNode);
            container2.AddFacility(new SynchronizeFacility());

            container2.Register(Component.For <DummyForm>().Named("dummy.form.class"));
            var model   = container2.Kernel.GetHandler("dummy.form.class").ComponentModel;
            var options = ProxyUtil.ObtainProxyOptions(model, false);

            Assert.IsNotNull(options, "Proxy options should not be null");
            Assert.IsTrue(options.Hook.Resolve(container2.Kernel, CreationContext.CreateEmpty()) is DummyProxyHook,
                          "Proxy hook should be a DummyProxyHook");
        }
Exemple #23
0
        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.Name.StartsWith("get_") && !invocation.Method.ReturnType.IsPrimitive)
            {
                var value = invocation.MethodInvocationTarget.Invoke(invocation.InvocationTarget, invocation.Arguments);

                if (IsTypeRegistered(invocation.Method.ReturnType))
                {
                    if (value == null || !ProxyUtil.IsProxy(value))
                    {
                        var invokedProperty = invocation.TargetType.GetProperty(invocation.Method.Name.Substring(4));
                        value = this.LoadData(invocation.InvocationTarget, invokedProperty);
                        invokedProperty.SetValue(invocation.InvocationTarget, value);
                    }
                }
            }

            invocation.Proceed();
        }
        protected override MetaMethod GetMethodToGenerate(MethodInfo method, IProxyGenerationHook hook, bool isStandalone)
        {
            if (ProxyUtil.IsAccessibleMethod(method) == false)
            {
                return(null);
            }

            var interceptable = AcceptMethodPreScreen(method, true, hook);

            if (!interceptable)
            {
                //we don't need to do anything...
                return(null);
            }

            var accepted = hook.ShouldInterceptMethod(type, method);

            return(new MetaMethod(method, method, isStandalone, accepted, hasTarget: true));
        }
Exemple #25
0
        internal static void CommitUpdate(bool isUserAdmin, String outcome, String fromVersion, String toVersion, String executablePath, String culture)
        {
            if (isUserAdmin)
            {
                return;
            }

            try
            {
                using (WebClient webClient = ProxyUtil.InitWebClientProxy(executablePath, culture))
                {
                    webClient.Headers.Add("user-agent", String.Format("DtPad Updater ({0})", AssemblyUtil.AssemblyVersion));
                    webClient.DownloadString(String.Format("{0}updates.php?from={1}&to={2}&env=prod&out={3}", ConstantUtil.actionsRepository, fromVersion, toVersion, outcome));
                }
            }
            catch (Exception)
            {
            }
        }
Exemple #26
0
        private static bool IsAccessibleToDynamicProxy(Type type)
        {
            return(AccessibleToDynamicProxyCache.GetOrAdd(type, IsAccessibleImpl));

            bool IsAccessibleImpl(Type t)
            {
                if (!ProxyUtil.IsAccessible(t))
                {
                    return(false);
                }

                if (type.IsGenericType && !type.IsGenericTypeDefinition)
                {
                    return(t.GetGenericArguments().All(IsAccessibleToDynamicProxy));
                }

                return(true);
            }
        }
Exemple #27
0
        public void TestServiceRequestConstructorInjection()
        {
            using var scope = _Container.OpenScope();

            var emptyService = scope.Resolve <EmptyServiceWithInfo>();

            Assert.NotNull(emptyService);
            Assert.NotNull(emptyService.ServiceWithParentInfo);
            Assert.NotNull(emptyService.ServiceWithParentInfo.ParentServiceRequestInfo);
            var parentServiceRequestInfo1 = emptyService.ServiceWithParentInfo.ParentServiceRequestInfo;

            Assert.AreEqual(typeof(EmptyServiceWithInfo), parentServiceRequestInfo1.ImplementationType);
            Assert.AreEqual(typeof(EmptyServiceWithInfo), parentServiceRequestInfo1.RequestInfo.ImplementationType);

            var simpleService = scope.Resolve <SimpleServiceWithTransaction>();

            Assert.NotNull(simpleService);
            var parentServiceRequestInfo2 = simpleService.ServiceWithParentInfo.ParentServiceRequestInfo;

            Assert.AreEqual(typeof(SimpleServiceWithTransaction), parentServiceRequestInfo2.ImplementationType, "ImplementationType should base (without proxy)");
            Assert.IsTrue(ProxyUtil.IsProxyType(parentServiceRequestInfo2.RequestInfo.ImplementationType), "Request.ImplementationType should be proxy type");

            var simpleService2 = scope.Resolve <IServiceWithTransaction>();

            Assert.NotNull(simpleService2);
            var parentServiceRequestInfo3 = simpleService2.ServiceWithParentInfo.ParentServiceRequestInfo;

            Assert.AreEqual(typeof(SimpleServiceWithTransaction), parentServiceRequestInfo3.ImplementationType, "ImplementationType should base (without proxy)");

            var serviceAccessor = scope.Resolve <ServiceAccessor>();

            Assert.NotNull(serviceAccessor);
            Assert.NotNull(serviceAccessor.Service1);
            Assert.NotNull(serviceAccessor.Service2);
            var parentServiceRequestInfo4 = serviceAccessor.Service1.ServiceWithParentInfo.ParentServiceRequestInfo;
            var parentServiceRequestInfo5 = serviceAccessor.Service2.ServiceWithParentInfo.ParentServiceRequestInfo;

            Assert.AreEqual(typeof(SimpleServiceWithTransaction), parentServiceRequestInfo4.ImplementationType, "ImplementationType should base (without proxy)");
            Assert.IsTrue(ProxyUtil.IsProxyType(parentServiceRequestInfo4.RequestInfo.ImplementationType), "Request.ImplementationType should be proxy type");
            Assert.AreEqual(typeof(SimpleServiceWithTransaction2), parentServiceRequestInfo5.ImplementationType, "ImplementationType should base (without proxy)");
            Assert.IsTrue(ProxyUtil.IsProxyType(parentServiceRequestInfo5.RequestInfo.ImplementationType), "Request.ImplementationType should be proxy type");
        }
Exemple #28
0
        public void Methods_made_visible_by_InternalsVisibleTo_can_be_intercepted(Type methodClass)
        {
            var method = methodClass.GetMethod(
                "Method",
                BindingFlags.NonPublic | BindingFlags.Instance
                );

            Assume.That(ProxyUtil.IsAccessible(method)); // because this assembly makes its internals visible to DynamicProxy

            var realObj = (IMethodClass)Activator.CreateInstance(methodClass);

            Assert.Throws <Exception>(realObj.InvokeMethod);

            var proxy = (IMethodClass)generator.CreateClassProxy(
                methodClass,
                new DoNothingInterceptor()
                );

            Assert.DoesNotThrow(proxy.InvokeMethod);
        }
Exemple #29
0
        public bool ShouldCreateProxy(ComponentModel model)
        {
            if (model.HasInterceptors)
            {
                return(true);
            }

            var options = ProxyUtil.ObtainProxyOptions(model, false);

            if (options != null && options.RequiresProxy)
            {
                return(true);
            }
            if (selectors != null && selectors.Any(s => s.HasInterceptors(model)))
            {
                return(true);
            }

            return(false);
        }
        protected virtual void CollectFromConfiguration(ComponentModel model)
        {
            if (model.Configuration == null)
            {
                return;
            }

            var interceptors = model.Configuration.Children["interceptors"];

            if (interceptors == null)
            {
                return;
            }

            CollectInterceptors(model, interceptors);
            var options = ProxyUtil.ObtainProxyOptions(model, true);

            CollectSelector(interceptors, options);
            CollectHook(interceptors, options);
        }