public override void Proceed()
        {
            var expectation = stubMessageBus.GetExpectationFor(Request.GetType());

            if (expectation == null)
            {
                var response = (Response)Activator.CreateInstance(Request.GetResponseType());
                response.CorrelationGuid = Request.CorrelationGuid;
                Response = GetSerializedVersion(response);
            }
            else
            {
                Response = GetSerializedVersion(expectation.Execute(Request));
            }

            if(Request.IsSideEffectFree)
            {
                try
                {
                    var options = new ProxyGenerationOptions(new NonVirtualCheckProxyGenerationHook());
                    var proxyGen = new ProxyGenerator();
                    proxyGen.CreateClassProxy(Request.GetResponseType(), options);
                }
                catch (Exception ex)
                {
                    throw new ColomboTestSupportException(string.Format("Response {0} cannot be proxied, probably because one or several of its members are not virtual.", Request.GetResponseType()), ex);
                }
            }
        }
        /// <summary>
        /// Decoration request
        /// </summary>
        /// <param name="context">Context info</param>
        /// <remarks>do not have to decorate, but may if it wants to. sorta..</remarks>
        public void Decorate(DecoratorContext context)
        {
            if (!CanDecorate(context))
                return;

            var options = new ProxyGenerationOptions();

            var services = context.Services;
            if (IgnoreClassAsService && services.Length > 1)
                services = services.Where(x => !x.IsClass).ToArray();

            var generator = new ProxyGenerator();
            if (services.Any(x => x.IsClass))
            {
                if (services.Length > 1)
                    throw new InvalidOperationException(
                        "A class that register itself as a service may not also be registered with interfaces. See the remarks in the IgnoreClassAsService property.");

                var clazz = context.Services.Single(x => x.IsClass);
                context.Instance = generator.CreateClassProxyWithTarget(clazz, context.Instance,
                                                                        CreateInterceptor(context));
            }
            else
            {
                var others = services.Where(x => x.IsInterface).Skip(1);
                var first = services.First();
                context.Instance = generator.CreateInterfaceProxyWithTarget
                    (first, others.ToArray(), context.Instance,
                     CreateInterceptor(context));
            }

        }
		public object Generate(IProxyBuilder builder, ProxyGenerationOptions options, IInterceptor[] interceptors)
		{
			var type = GetProxyType(builder);
			var instance = GetProxyInstance(type,interceptors);
			var method = GetInvokeDelegate(instance);
			return method;
		}
        private static ProxyGeneratorResult GenerateProxy(
            Type typeOfProxy,
            ProxyGenerationOptions options,
            IEnumerable<Type> additionalInterfacesToImplement,
            IEnumerable<object> argumentsForConstructor,
            IFakeCallProcessorProvider fakeCallProcessorProvider)
        {
            Guard.AgainstNull(typeOfProxy, nameof(typeOfProxy));
            Guard.AgainstNull(additionalInterfacesToImplement, nameof(additionalInterfacesToImplement));
            Guard.AgainstNull(fakeCallProcessorProvider, nameof(fakeCallProcessorProvider));

            if (typeOfProxy.GetTypeInfo().IsValueType)
            {
                return GetProxyResultForValueType(typeOfProxy);
            }

            if (typeOfProxy.GetTypeInfo().IsSealed)
            {
                return new ProxyGeneratorResult(DynamicProxyResources.ProxyIsSealedTypeMessage.FormatInvariant(typeOfProxy));
            }

            GuardAgainstConstructorArgumentsForInterfaceType(typeOfProxy, argumentsForConstructor);

            return CreateProxyGeneratorResult(typeOfProxy, options, additionalInterfacesToImplement, argumentsForConstructor, fakeCallProcessorProvider);
        }
        public void CanCreateMixinWithClassInterceptors()
        {
            var options = new ProxyGenerationOptions();
            options.AddMixinInstance(new Dictionary<int, int>());

            var builder = new ContainerBuilder();
            builder.RegisterType<C>().EnableClassInterceptors(options);
            builder.RegisterType<AddOneInterceptor>();
            builder.RegisterType<AddTenInterceptor>();
            var container = builder.Build();
            var i = 10;
            var cpt = container.Resolve<C>(TypedParameter.From(i));

            var dict = cpt as IDictionary<int, int>;

            Assert.NotNull(dict);

            dict.Add(1, 2);

            Assert.Equal(2, dict[1]);

            dict.Clear();

            Assert.Empty(dict);
        }
Пример #6
0
        internal static IController TrySetActionInvoker(this IController iController, IGlimpseLogger logger)
        {
            var controller = iController as Controller;
            if (controller == null)
            {
                //TODO: Add Logging
                return iController;
            }

            var actionInvoker = controller.ActionInvoker;

            if (actionInvoker.CanSupportDynamicProxy(logger))
            {
                var proxyConfig = new Dictionary<string, IInterceptor>
                                      {
                                          {"GetFilters", new GetFiltersInterceptor()},
                                          {"InvokeActionResult", new InvokeActionResultInterceptor()},
                                          {"InvokeActionMethod",new InvokeActionMethodInterceptor()}
                                      };

                var proxyGenerator = new ProxyGenerator();
                var proxyGenOptions = new ProxyGenerationOptions(new SimpleProxyGenerationHook(logger, proxyConfig.Keys.ToArray())) { Selector = new SimpleInterceptorSelector(proxyConfig) };
                var newInvoker = (ControllerActionInvoker)proxyGenerator.CreateClassProxy(actionInvoker.GetType(), proxyGenOptions, proxyConfig.Values.ToArray());
                controller.ActionInvoker = newInvoker;
            }

            return controller;
        }
Пример #7
0
        public override object GetFieldInterceptionProxy()
		{
			var proxyGenerationOptions = new ProxyGenerationOptions();
			var interceptor = new LazyFieldInterceptor();
			proxyGenerationOptions.AddMixinInstance(interceptor);
			return ProxyGenerator.CreateClassProxy(PersistentClass, proxyGenerationOptions, interceptor);
		}
Пример #8
0
        public void Register(ContainerBuilder builder)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            ProxyGenerationOptions ProxyOption = new ProxyGenerationOptions()
            {
                Selector = new InterceptorSelector()
            };
            //注册所有服务
            builder.RegisterAssemblyTypes(assembly)
               .Where(type => type.FullName.EndsWith("ApplicationService") && type.IsClass)
               .AsImplementedInterfaces()
               .EnableInterfaceInterceptors(ProxyOption)
               ;//.InterceptedBy(typeof(MethodInvacationValidateInterceptor), typeof(UnitOfWorkInterceptor));

            //注册DbContext
            builder.RegisterType<SampleEntities>().As<DbContext>();

            //注册所有泛型仓储
            var finder = new WebAppTypeFinder();
            var allEntityTypes = finder.FindClassOfType(typeof(IEntity));
            foreach (var entityType in allEntityTypes)
            {
                var genericRepositoryType = typeof(IRepository<>).MakeGenericType(entityType);
                var implType = typeof(EfRepository<,>).MakeGenericType(typeof(DbContext), entityType);
                builder.RegisterType(implType).As(genericRepositoryType);
            }

            builder.RegisterType<CallCurrentUnitOfWorkProvider>().As<ICurrentUnitOfWorkProvider>();
            builder.RegisterType<UnitOfWorkDbContextProvider<DbContext>>().As<IDbContextProvider<DbContext>>();
            builder.RegisterType<EfDbContextProvider<DbContext>>().Keyed<IDbContextProvider<DbContext>>("Default");
            builder.RegisterType<UnitOfWorkManager>().As<IUnitOfWorkManager>();
            builder.RegisterType<EfUnitOfWork>().As<IUnitOfWork>();
        }
        /// <inheritdoc />
        public object Create(object target, Type typeOfProxy,
                                                    Type[] additionalInterfacesOfProxy)
        {
            Check.MustNotNull("target", "target");
            Check.MustNotNull("typeToProxy", "typeToProxy");

            var aspects = _aspectsFinder.FindAspects(target.GetType());
            if (!aspects.Any())
            {
                return target;
            }

            var options = new ProxyGenerationOptions
            {
                Selector = new PointcutAspectInterceptorSelector()
            };
            foreach (var instance in this.GetMixinInstances(target.GetType(), aspects))
            {
                options.AddMixinInstance(instance);
            }

            var interceptors = this.GetInterceptors(target.GetType(), aspects);
            if (typeOfProxy.IsInterface)
            {
                return _proxyGenerator.CreateInterfaceProxyWithTarget(typeOfProxy,
                                                       additionalInterfacesOfProxy,
                                                       target, options, interceptors);
            }
            else
            {
                return _proxyGenerator.CreateClassProxyWithTarget(typeOfProxy,
                                                       additionalInterfacesOfProxy,
                                                       target, options, interceptors);
            }
        }
Пример #10
0
		public Type CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
		{
			AssertValidType(interfaceToProxy);
			AssertValidTypes(additionalInterfacesToProxy);

			var generator = new InterfaceProxyWithoutTargetGenerator(scope, interfaceToProxy) { Logger = logger };
			return generator.GenerateCode(typeof(object), additionalInterfacesToProxy, options);
		}
		// 重载 InterfaceProxyWithTargetInterfaceContributor 中的方法,以指定使用扩展的 InvocationType 生成方法执行类
		protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod)
		{
			if (!method.Proxyable)
			{
				return new MinimialisticMethodGenerator(method, overrideMethod);
			}
			return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), this.GetInvocationType(method, @class, options), this.getTargetExpression, overrideMethod, null);
		}
		// 重载 InterfaceProxyWithTargetInterfaceContributor 中的方法,以指定使用扩展的 InvocationType 生成方法执行类
		protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod)
		{
			if (!method.Proxyable)
			{
				return new ForwardingMethodGenerator(method, overrideMethod, (c, m) => c.GetField("__target"));
			}
			return new MethodWithInvocationGenerator(method, @class.GetField("__interceptors"), this.GetInvocationType(method, @class, options), (c, m) => c.GetField("__target").ToExpression(), overrideMethod, null);
		}
Пример #13
0
		private void ReleaseHook(ProxyGenerationOptions proxyGenOptions, IKernel kernel)
		{
			if (proxyGenOptions.Hook == null)
			{
				return;
			}
			kernel.ReleaseComponent(proxyGenOptions.Hook);
		}
Пример #14
0
		public virtual Type CreateClassProxy(Type theClass, ProxyGenerationOptions options)
		{
			AssertValidType(theClass);

			ClassProxyGenerator generator = new ClassProxyGenerator(scope, theClass);

			return generator.GenerateCode(null, options);
		}
Пример #15
0
		public Type CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
		{
			AssertValidType(classToProxy);
			AssertValidTypes(additionalInterfacesToProxy);

			var generator = new ClassProxyGenerator(scope, classToProxy) { Logger = logger };
			return generator.GenerateCode(additionalInterfacesToProxy, options);
		}
Пример #16
0
		public Type CreateInterfaceProxyTypeWithTargetInterface(Type theInterface, ProxyGenerationOptions options)
		{
			AssertValidType(theInterface);

			InterfaceProxyWithTargetInterfaceGenerator generator =
				new InterfaceProxyWithTargetInterfaceGenerator(scope, theInterface);

			return generator.GenerateCode(theInterface, null, options);
		}
Пример #17
0
		public Type CreateClassProxy(Type theClass, Type[] interfaces, ProxyGenerationOptions options)
		{
			AssertValidType(theClass);
			AssertValidTypes(interfaces);

			ClassProxyGenerator generator = new ClassProxyGenerator(scope, theClass);

			return generator.GenerateCode(interfaces, options);
		}
Пример #18
0
		/// <summary>
		/// Creates a context - which is used to guid custom proxy
		/// generation.
		/// </summary>
		/// <param name="mixins">Array of mixins to be registered</param>
		/// <returns>A GeneratorContext instance</returns>
		private static ProxyGenerationOptions CreateProxyGenerationOptions(object[] mixins)
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			foreach (object mixin in mixins)
			{
				options.AddMixinInstance(mixin);
			}
			return options;
		}
 public TypedPageActivator()
 {
     _generator = new ProxyGenerator();
     _options = new ProxyGenerationOptions(new PageTypePropertiesProxyGenerationHook());
     _interceptors = new IInterceptor[] 
                        {
                            new PageTypePropertyInterceptor()
                        };
 }
Пример #20
0
		public object Generate(IProxyBuilder builder, ProxyGenerationOptions options, IInterceptor[] interceptors, ComponentModel model,
		                       CreationContext context)
		{
			var targetDelegateType = context.RequestedType;
			var type = GetProxyType(builder, targetDelegateType);
			var instance = GetProxyInstance(type, interceptors);
			var method = GetInvokeDelegate(instance, targetDelegateType);
			return method;
		}
Пример #21
0
 public void Foo1()
 {
     ProxyGenerator generator = new ProxyGenerator();
     //Castle.DynamicProxy.IInterceptor[] interceptors = { new MyCastleInterceptor() };
     var options = new ProxyGenerationOptions(new InterceptorFilter()) { Selector = new InterceptorSelector() };
     CastleUserProcessor userProcessor = generator.CreateClassProxy<CastleUserProcessor>(options,new MyCastleInterceptor(), new SimpleLogInterceptor());
     User user = new User() { Name = "lee", PassWord = "******" };
     userProcessor.RegUser(user);
 }
Пример #22
0
        /// <summary>
        /// Initializes the elements in the Page Object.
        /// </summary>
        /// <param name="driver">The driver used to find elements on the page.</param>
        /// <param name="page">The Page Object to be populated with elements.</param>
        public static void InitElements(ISearchContext driver, object page)
        {
            const BindingFlags BindingOptions = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
            if (page == null)
            {
                throw new ArgumentNullException("page", "page cannot be null");
            }

            var type = page.GetType();
            var fields = type.GetFields(BindingOptions);
            var properties = type.GetProperties(BindingOptions);
            var members = new List<MemberInfo>(fields);
            members.AddRange(properties);

            foreach (var member in members)
            {
                var attributes = member.GetCustomAttributes(typeof(FindsByAttribute), true);
                foreach (var attribute in attributes)
                {
                    var castedAttribute = (FindsByAttribute)attribute;
                    var generator = new ProxyGenerator();

                    var cacheAttributeType = typeof(CacheLookupAttribute);
                    var cache = member.GetCustomAttributes(cacheAttributeType, true).Length != 0 || member.DeclaringType.GetCustomAttributes(cacheAttributeType, true).Length != 0;

                    var interceptor = new ProxiedWebElementInterceptor(driver, castedAttribute.Bys, cache);

                    var options = new ProxyGenerationOptions
                        {
                            BaseTypeForInterfaceProxy = typeof(WebElementProxyComparer)
                        };

                    var field = member as FieldInfo;
                    var property = member as PropertyInfo;
                    if (field != null)
                    {
                        var proxyElement = generator.CreateInterfaceProxyWithoutTarget(
                            typeof(IWrapsElement),
                            new[] { field.FieldType },
                            options,
                            interceptor);

                        field.SetValue(page, proxyElement);
                    }
                    else if (property != null)
                    {
                        var proxyElement = generator.CreateInterfaceProxyWithoutTarget(
                            typeof(IWrapsElement),
                            new[] { property.PropertyType },
                            options,
                            interceptor);

                        property.SetValue(page, proxyElement, null);
                    }
                }
            }
        }
Пример #23
0
		public Type CreateClassProxyTypeWithTarget(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
		{
			this.AssertValidType(classToProxy);
			this.AssertValidTypes(additionalInterfacesToProxy);
			ClassProxyWithTargetGenerator generator = new ClassProxyWithTargetGenerator(this.scope, classToProxy, additionalInterfacesToProxy, options)
			{
				Logger = this.logger
			};
			return generator.GetGeneratedType();
		}
Пример #24
0
		public Type CreateInterfaceProxyTypeWithTarget(Type theInterface, Type[] interfaces, Type targetType,
		                                               ProxyGenerationOptions options)
		{
			AssertValidType(theInterface);
			AssertValidTypes(interfaces);

			InterfaceProxyWithTargetGenerator generator = new InterfaceProxyWithTargetGenerator(scope, theInterface);

			return generator.GenerateCode(targetType, interfaces, options);
		}
Пример #25
0
		public Type CreateInterfaceProxyTypeWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Type targetType,
													   ProxyGenerationOptions options)
		{
			AssertValidType(interfaceToProxy);
			AssertValidTypes(additionalInterfacesToProxy);

			InterfaceProxyWithTargetGenerator generator = new InterfaceProxyWithTargetGenerator(scope, interfaceToProxy);

			return generator.GenerateCode(targetType, additionalInterfacesToProxy, options);
		}
		protected override ArgumentReference[] GetBaseCtorArguments(Type targetFieldType, ProxyGenerationOptions proxyGenerationOptions, out ConstructorInfo baseConstructor)
		{
			if (proxyGenerationOptions.Selector == null)
			{
				baseConstructor = InvocationMethods.CompositionInvocationConstructorNoSelector;
				return new ArgumentReference[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(MethodInfo)), new ArgumentReference(typeof(object[])) };
			}
			baseConstructor = InvocationMethods.CompositionInvocationConstructorWithSelector;
			return new ArgumentReference[] { new ArgumentReference(targetFieldType), new ArgumentReference(typeof(object)), new ArgumentReference(typeof(IInterceptor[])), new ArgumentReference(typeof(MethodInfo)), new ArgumentReference(typeof(object[])), new ArgumentReference(typeof(IInterceptorSelector)), new ArgumentReference(typeof(IInterceptor[]).MakeByRefType()) };
		}
Пример #27
0
		public Type CreateInterfaceProxyTypeWithoutTarget(Type theInterface, Type[] interfaces, ProxyGenerationOptions options)
		{
			AssertValidType(theInterface);
			AssertValidTypes(interfaces);

			InterfaceProxyWithoutTargetGenerator generatorWithoutTarget =
				new InterfaceProxyWithoutTargetGenerator(scope, theInterface);

			return generatorWithoutTarget.GenerateCode(typeof(object), interfaces, options);
		}
 /// <summary>
 /// Generates the class defined by the provided class emitter.
 /// </summary>
 /// <param name="class">
 /// The <see cref="Castle.DynamicProxy.Generators.Emitters.ClassEmitter"/>
 /// being used to build the target type.
 /// </param>
 /// <param name="options">The options to use during proxy generation.</param>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if <paramref name="class" /> is <see langword="null" />.
 /// </exception>
 /// <remarks>
 /// <para>
 /// This overridden version of the method does everything that the base
 /// <see cref="Castle.DynamicProxy.Contributors.ProxyInstanceContributor.Generate"/>
 /// method does but it skips the part where it checks for non-inherited
 /// attributes and copies them over from the proxy target.
 /// </para>
 /// </remarks>
 public override void Generate(ClassEmitter @class, ProxyGenerationOptions options)
 {
     if (@class == null)
     {
         throw new ArgumentNullException("class");
     }
     FieldReference field = @class.GetField("__interceptors");
     this.ImplementGetObjectData(@class);
     this.ImplementProxyTargetAccessor(@class, field);
 }
        public object Intercept(object value)
        {
            ProxyGenerationOptions options = new ProxyGenerationOptions();

            var interfaces = value.GetType().GetInterfaces();
            Type proxyInterface = interfaces.FirstOrDefault();
            Type[] additionalInterfaces = interfaces.Skip(1).ToArray();
            var proxy = _generator.CreateInterfaceProxyWithTargetInterface(proxyInterface, additionalInterfaces, value, _interceptors);
            return proxy;
        }
Пример #30
0
        public void Register(ContainerBuilder builder)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            ProxyGenerationOptions ProxyOption = new ProxyGenerationOptions()
            {
                Selector = new InterceptorSelector()
            };

            builder.RegisterControllers(assembly);//.EnableClassInterceptors(ProxyOption);
                    
        }