public void CreateInterfaceProxyWithTargetInterface()
		{
			ProxyGenerator generator = new ProxyGenerator();
			IFooExtended proxiedFoo = (IFooExtended)generator.CreateInterfaceProxyWithTargetInterface(
				typeof(IFooExtended), new ImplementedFoo(), new StandardInterceptor());
			proxiedFoo.FooExtended();
		}
Ejemplo n.º 2
0
        internal static IServiceRemotingListener CreateServiceRemotingListener <TImplementation>(
            ServiceContext context,
            Type[] ifaces,
            IServiceProvider container)
        {
            var  client     = container.GetRequiredService <TelemetryClient>();
            Type firstIface = ifaces[0];

            Type[] additionalIfaces = ifaces.Skip(1).ToArray();
            var    gen  = new ProxyGenerator();
            var    impl = (IService)gen.CreateInterfaceProxyWithTargetInterface(
                firstIface,
                additionalIfaces,
                (object)null,
                new InvokeInNewScopeInterceptor <TImplementation>(container),
                new LoggingServiceInterceptor(context, client));

            return(new FabricTransportServiceRemotingListener(
                       context,
                       new ActivityServiceRemotingMessageDispatcher(context, impl, null)));
        }
        public void InterceptCatchesExceptions()
        {
            var telemetryChannel = new FakeChannel();
            var config           = new TelemetryConfiguration("00000000-0000-0000-0000-000000000001", telemetryChannel);
            var client           = new TelemetryClient(config);


            var service = new Mock <IFakeService>();

            service.Setup(s => s.TestServiceMethod()).Throws(new InvalidOperationException("Test Exception Text"));

            var collection = new ServiceCollection();

            collection.AddSingleton(client);
            MockBuilder.RegisterStatelessServiceContext(collection);
            collection.AddSingleton(service.Object);
            ServiceProvider provider = collection.BuildServiceProvider();

            var gen  = new ProxyGenerator();
            var impl = (IFakeService)gen.CreateInterfaceProxyWithTargetInterface(
                typeof(IFakeService),
                new Type[0],
                (object)null,
                new InvokeInNewScopeInterceptor <IFakeService>(provider));

            var ex = (((Func <object>)(() => impl.TestServiceMethod()))).Should().Throw <InvalidOperationException>().Which;

            ex.Message.Should().Be("Test Exception Text");

            client.Flush();

            RequestTelemetry requestTelemetry = telemetryChannel.Telemetry.OfType <RequestTelemetry>().FirstOrDefault();

            requestTelemetry.Should().NotBeNull();
            requestTelemetry.Success.Should().BeFalse();
            ExceptionTelemetry exceptionTelemetry = telemetryChannel.Telemetry.OfType <ExceptionTelemetry>().FirstOrDefault();

            exceptionTelemetry.Should().NotBeNull();
            exceptionTelemetry.Exception.Should().BeSameAs(ex);
        }
Ejemplo n.º 4
0
        public static void AddApplication(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <ProjectSettings>(configuration.Bind);

            services.AddAutoMapper(typeof(ApplicationRegistry));
            services.AddValidatorsFromAssembly(typeof(ApplicationRegistry).Assembly);
            services.AddDNTNumbering(options =>
            {
                options.NumberedEntityMap[typeof(Task)] = new NumberedEntityOption
                {
                    Start       = 100,
                    Prefix      = "Task-",
                    IncrementBy = 5
                };
            });
            services.Scan(scan => scan
                          .FromCallingAssembly()
                          .AddClasses(classes => classes.AssignableTo <ISingletonDependency>())
                          .AsMatchingInterface()
                          .WithSingletonLifetime()
                          .AddClasses(classes => classes.AssignableTo <IScopedDependency>())
                          .AsMatchingInterface()
                          .WithScopedLifetime()
                          .AddClasses(classes => classes.AssignableTo <ITransientDependency>())
                          .AsMatchingInterface()
                          .WithTransientLifetime()
                          .AddClasses(classes => classes.AssignableTo(typeof(IBusinessEventHandler <>)))
                          .AsImplementedInterfaces()
                          .WithTransientLifetime());

            foreach (var descriptor in services.Where(s => typeof(IApplicationService).IsAssignableFrom(s.ServiceType))
                     .ToList())
            {
                services.Decorate(descriptor.ServiceType, (target, serviceProvider) =>
                                  ProxyGenerator.CreateInterfaceProxyWithTargetInterface(
                                      descriptor.ServiceType,
                                      target, serviceProvider.GetRequiredService <ValidationInterceptor>(),
                                      (IInterceptor)serviceProvider.GetRequiredService <TransactionInterceptor>()));
            }
        }
Ejemplo n.º 5
0
 public static IServiceCollection AddApp(this IServiceCollection services)
 {
     return(services
            .AddSingleton <IStartup, ST.Startup>()
            .AddSingleton <MainForm>()
            .AddSingleton <IAppConfiguration, AppConfiguration>()
            .AddSingleton <IRepoHolder, RepoHolder>()
            .AddSingleton <IGitFileRepo, GitFileRepo>()
            .AddSingleton <IProjectFileRepo, ProjectFileRepo>()
            .AddSingleton <ITabsRepoBuilder, TabsRepoBuilder>()
            .AddSingleton <IAppSemaphoreSlim, AppSemaphoreSlim>()
            .AddSingleton <IGitVersion, RepoCommandProcessor>()
            .AddSingleton <ILoggerFactory>(sp =>
     {
         var eventSetting = new EventLogSettings
         {
             Filter = (msg, level) => level > LogLevel.Debug,
             SourceName = "GitLooker"
         };
         var provider = new EventLogLoggerProvider(eventSetting);
         return new LoggerFactory(new[] { provider });
     })
            .AddLogging()
            .AddSingleton(typeof(ILogger <>), typeof(Logger <>))
            .AddSingleton <IGitValidator, GitValidator>()
            .AddTransient <IProcessShell, ProcessShell>()
            .AddTransient <IRepoCommandProcessor, RepoCommandProcessor>()
            .AddTransient <RepoCommandProcessorController>()
            .AddTransient <SemaphoreInteractionInterceptor>()
            .AddTransient <TabReposControl>()
            .AddTransient(service =>
     {
         var myInterceptedClass = service.GetService <RepoCommandProcessorController>();
         var interceptor = service.GetService <SemaphoreInteractionInterceptor>();
         var proxy = new ProxyGenerator();
         return proxy.CreateInterfaceProxyWithTargetInterface <IRepoCommandProcessorController>(myInterceptedClass, interceptor);
     })
            .AddTransient <RepoControl>());
 }
Ejemplo n.º 6
0
        public void Cache_With_AOP()
        {
            ProxyGenerator proxyGenerator  = new ProxyGenerator();
            IRepository    repository      = new Repository();
            IRepository    repositoryProxy = proxyGenerator.CreateInterfaceProxyWithTargetInterface <IRepository>(repository, new CacheInterceptor());

            Debug.WriteLine("First run...");
            IList <string> languages = repositoryProxy.GetLanguages();

            Assert.AreEqual <string>("English", languages[0]);
            Assert.AreEqual <string>("Japanese", languages[1]);
            Assert.AreEqual <string>("Simplified Chinese", languages[2]);
            Assert.AreEqual <string>("Traditional Chinese", languages[3]);

            Debug.WriteLine("Second run...");
            IList <string> cachedLanguages = repositoryProxy.GetLanguages();

            Assert.AreEqual <string>("English", cachedLanguages[0]);
            Assert.AreEqual <string>("Japanese", cachedLanguages[1]);
            Assert.AreEqual <string>("Simplified Chinese", cachedLanguages[2]);
            Assert.AreEqual <string>("Traditional Chinese", cachedLanguages[3]);

            Debug.WriteLine("First run...");
            IList <Setting> settings = repositoryProxy.GetSettings();

            Assert.AreEqual <string>("Domain", settings[0].Name);
            Assert.AreEqual <string>("dev.pete.tw", settings[0].Value);
            Assert.AreEqual <string>("Administrator", settings[1].Name);
            Assert.AreEqual <string>("Pete", settings[1].Value);

            Debug.WriteLine("Second run...");
            IList <Setting> cachedSettings = repositoryProxy.GetSettings();

            Assert.AreEqual <string>("Domain", cachedSettings[0].Name);
            Assert.AreEqual <string>("dev.pete.tw", cachedSettings[0].Value);
            Assert.AreEqual <string>("Administrator", cachedSettings[1].Name);
            Assert.AreEqual <string>("Pete", cachedSettings[1].Value);
        }
        public static void AddApplication(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <ProjectSetting>(configuration.Bind);

            services.AddAutoMapper(typeof(ApplicationRegistry));
            services.AddValidatorsFromAssemblyContaining(typeof(ApplicationRegistry));

            services.Scan(scan => scan
                          .FromCallingAssembly()
                          .AddClasses(classes => classes.AssignableTo <ISingletonDependency>())
                          .AsMatchingInterface()
                          .WithSingletonLifetime()
                          .AddClasses(classes => classes.AssignableTo <IScopedDependency>())
                          .AsMatchingInterface()
                          .WithScopedLifetime()
                          .AddClasses(classes => classes.AssignableTo <ITransientDependency>())
                          .AsMatchingInterface()
                          .WithTransientLifetime()
                          .AddClasses(classes => classes.AssignableTo(typeof(IBusinessEventHandler <>)))
                          .AsImplementedInterfaces()
                          .WithTransientLifetime()
                          .AddClasses(classes => classes.AssignableTo(typeof(IModelValidator <>)))
                          .AsImplementedInterfaces()
                          .WithTransientLifetime()
                          .AddClasses(classes => classes.AssignableTo(typeof(IMapper <,>)))
                          .AsImplementedInterfaces()
                          .WithTransientLifetime());

            foreach (var descriptor in services.Where(s => typeof(IApplicationService).IsAssignableFrom(s.ServiceType))
                     .ToList())
            {
                services.Decorate(descriptor.ServiceType, (target, serviceProvider) =>
                                  ProxyGenerator.CreateInterfaceProxyWithTargetInterface(
                                      descriptor.ServiceType,
                                      target, serviceProvider.GetRequiredService <ValidationInterceptor>(),
                                      serviceProvider.GetRequiredService <TransactionInterceptor>()));
            }
        }
Ejemplo n.º 8
0
        public override object Create(IKernel kernel, object instance, ComponentModel model,
                                      CreationContext context, params object[] constructorArguments)
        {
            var channelHolder = instance as IWcfChannelHolder;

            if (channelHolder == null)
            {
                throw new ArgumentException(string.Format("Given instance is not an {0}", typeof(IWcfChannelHolder)), "instance");
            }

            var isDuplex          = IsDuplex(channelHolder.RealProxy);
            var proxyOptions      = model.ObtainProxyOptions();
            var serviceContract   = model.GetServiceContract();
            var remainingServices = model.Services.Except(new[] { serviceContract });
            var generationOptions = CreateProxyGenerationOptions(serviceContract, proxyOptions, kernel, context);

            generationOptions.AddMixinInstance(channelHolder);
            var additionalInterfaces = GetInterfaces(remainingServices, proxyOptions, isDuplex);
            var interceptors         = GetInterceptors(kernel, model, serviceContract, channelHolder, context);

            return(generator.CreateInterfaceProxyWithTargetInterface(serviceContract,
                                                                     additionalInterfaces, channelHolder.Channel, generationOptions, interceptors));
        }
        /// <summary>
        /// Creates dynamically generated slim WCF client that supports OMiau authorization.
        /// </summary>
        /// <typeparam name="TChannel">Service interface</typeparam>
        /// <typeparam name="TSlimServiceClient">
        /// Slim client interface (must derive from <typeparamref name="TChannel"/>)</typeparam>
        /// <param name="realClient">Real service client</param>
        /// <param name="tokenService">Token service</param>
        /// <returns>Slim WCF client</returns>
        public static TSlimServiceClient CreateSlimClient <TChannel, TSlimServiceClient>(
            ClientBase <TChannel> realClient, ITokenService tokenService)
            where TChannel : class
            where TSlimServiceClient : class
        {
            if (realClient == null)
            {
                throw new ArgumentNullException(nameof(realClient));
            }
            if (tokenService == null)
            {
                throw new ArgumentNullException(nameof(tokenService));
            }
            if (!typeof(TChannel).IsAssignableFrom(typeof(TSlimServiceClient)))
            {
                throw new ArgumentNullException("Type arguments don't match.");
            }

            // Create a dispatcher for real client
            var dispatcher = new SlimServiceClientDispatcher <TChannel>(realClient);

            // Generate a "real object" of ILazyCatServiceSlimClient that will delegate calls
            // to the dispatcher
            var wrappedDispatcher = (TSlimServiceClient)ProxyGenerator.CreateInterfaceProxyWithoutTarget(
                typeof(TSlimServiceClient),
                dispatcher);

            // Create async interceptor
            var asyncInterceptor = new SlimServiceClientAsyncInterceptor <TSlimServiceClient>(
                wrappedDispatcher, () => realClient.InnerChannel, tokenService);

            // Glue everything together to get mind blowing wrapper Bacon Double Cheeseburger
            var wrappedSlimClient = ProxyGenerator.CreateInterfaceProxyWithTargetInterface(
                wrappedDispatcher, asyncInterceptor);

            return(wrappedSlimClient);
        }
Ejemplo n.º 10
0
        public void ExceptionLogsFailedRequest()
        {
            var telemetryChannel = new FakeChannel();
            var config           = new TelemetryConfiguration("00000000-0000-0000-0000-000000000001", telemetryChannel);
            var client           = new TelemetryClient(config);

            StatelessServiceContext ctx = MockBuilder.StatelessServiceContext();

            Mock <IFakeService> fakeService = new Mock <IFakeService>();

            fakeService.Setup(s => s.TestServiceMethod()).Throws(new InvalidOperationException("Test Exception Text"));

            var gen  = new ProxyGenerator();
            var impl = (IFakeService)gen.CreateInterfaceProxyWithTargetInterface(
                typeof(IFakeService),
                new Type[0],
                fakeService.Object,
                new LoggingServiceInterceptor(ctx, client));

            var ex = (((Func <object>)(() => impl.TestServiceMethod()))).Should().Throw <InvalidOperationException>().Which;

            ex.Message.Should().Be("Test Exception Text");

            client.Flush();
            List <RequestTelemetry> requestTelemetries =
                telemetryChannel.Telemetry.OfType <RequestTelemetry>().ToList();

            requestTelemetries.Should().ContainSingle();
            RequestTelemetry requestTelemetry = requestTelemetries[0];

            requestTelemetry.Success.Should().BeFalse();
            ExceptionTelemetry exceptionTelemetry = telemetryChannel.Telemetry.OfType <ExceptionTelemetry>().FirstOrDefault();

            exceptionTelemetry.Should().NotBeNull();
            exceptionTelemetry.Exception.Should().BeSameAs(ex);
        }
Ejemplo n.º 11
0
        public void ExceptionLogsFailedRequest()
        {
            var telemetryChannel = new FakeChannel();
            var config           = new TelemetryConfiguration("00000000-0000-0000-0000-000000000001", telemetryChannel);
            var client           = new TelemetryClient(config);

            StatelessServiceContext ctx = MockBuilder.StatelessServiceContext();

            Mock <IFakeService> fakeService = new Mock <IFakeService>();

            fakeService.Setup(s => s.TestServiceMethod()).Throws(new InvalidOperationException("Test Exception Text"));

            var gen  = new ProxyGenerator();
            var impl = (IFakeService)gen.CreateInterfaceProxyWithTargetInterface(
                typeof(IFakeService),
                new Type[0],
                fakeService.Object,
                new LoggingServiceInterceptor(ctx, client));

            var ex = Assert.ThrowsAny <InvalidOperationException>(() => impl.TestServiceMethod());

            Assert.Equal("Test Exception Text", ex.Message);

            client.Flush();
            List <RequestTelemetry> requestTelemetries =
                telemetryChannel.Telemetry.OfType <RequestTelemetry>().ToList();

            Assert.Single(requestTelemetries);
            RequestTelemetry requestTelemetry = requestTelemetries[0];

            Assert.False(requestTelemetry.Success);
            ExceptionTelemetry exceptionTelemetry = telemetryChannel.Telemetry.OfType <ExceptionTelemetry>().FirstOrDefault();

            Assert.NotNull(exceptionTelemetry);
            Assert.Same(ex, exceptionTelemetry.Exception);
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            #region 1.0 不使用StructureMap的情况
            //var service2=new ServiceTwo();
            //var service1=new ServiceOne(service2);
            //service1.DoWorkOne();
            #endregion

            #region 2.0 使用StructureMap
            //ObjectFactory.Initialize(config =>//不同的IOC工具初始化代码是不同的
            //{
            //    config.Scan(scanner =>
            //    {
            //        scanner.TheCallingAssembly();
            //        scanner.WithDefaultConventions();//使用默认的惯例
            //    });
            //    var proxyGenerator = new ProxyGenerator();
            //    var aspect = new LoggingAspect(new LoggingService());
            //    var service = new ServiceOne(new ServiceTwo());
            //    var result = proxyGenerator.CreateInterfaceProxyWithTargetInterface(typeof(IServiceOne), service, aspect);//应用切面
            //    config.For<IServiceOne>().Use((IServiceOne) result);//告诉StructureMap使用产生的动态代理
            //});


            //var service1 = ObjectFactory.GetInstance<IServiceOne>();
            //service1.DoWorkOne();
            #endregion

            #region 3.0 使用EnrichWith重构
            ObjectFactory.Initialize(config =>
            {
                config.Scan(scanner =>
                {
                    scanner.TheCallingAssembly();
                    scanner.WithDefaultConventions();
                });
                var proxyGenerator = new ProxyGenerator();
                //EnrichWith期待传入一个Func参数
                config.For <IServiceOne>().Use <ServiceOne>().EnrichWith(svc =>
                {
                    var aspect = new LoggingAspect(new LoggingService());
                    var result = proxyGenerator.CreateInterfaceProxyWithTargetInterface(typeof(IServiceOne), svc, aspect);
                    return(result);
                });
            });

            #endregion

            #region 4.0使用ProxyHelper重构
            ObjectFactory.Initialize(config =>
            {
                config.Scan(scanner =>
                {
                    scanner.TheCallingAssembly();
                    scanner.WithDefaultConventions();
                });
                var proxyHelper = new ProxyHelper();
                //注意Proxify方法本身以实参传入EnrichWith方法
                config.For <IServiceOne>().Use <ServiceOne>().EnrichWith(proxyHelper.Proxify <IServiceOne, LoggingAspect>);
            });
            #endregion
            Console.Read();
        }
Ejemplo n.º 13
0
        public static T Create <T>(T instance, IAsyncInterceptor interceptor) where T : class
        {
            T proxy = generator.CreateInterfaceProxyWithTargetInterface <T>(instance, interceptor);

            return(proxy);
        }
Ejemplo n.º 14
0
 public object Proxify <T, TK>(object obj) where TK : IInterceptor
 =>
 _proxyGenerator.CreateInterfaceProxyWithTargetInterface(typeof(T), obj,
                                                         ObjectFactory.Locator.GetInstance <TK>());
Ejemplo n.º 15
0
 public object Process(object target, IContext context)
 {
     return(_proxy.CreateInterfaceProxyWithTargetInterface(target.GetType().GetInterfaces().First(),
                                                           target.GetType().GetInterfaces(), target,
                                                           new DynamicProxyInterceptor()));
 }
Ejemplo n.º 16
0
 public TInterface CreateCannelWithRetries <TInterface>(IServiceProxy <TInterface> serviceProxy) where TInterface : class
 {
     return(proxyGenerator.CreateInterfaceProxyWithTargetInterface(serviceProxy.Channel, new ClientProxyRetryInterceptor()));
 }
Ejemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TInterface"></typeparam>
        /// <param name="interface"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static TInterface GenerateInterfaceProxy <TInterface>(this TInterface @interface, params IInterceptor[] interceptors) where TInterface : class
        {
            var proxyGenerator = new ProxyGenerator();

            return(proxyGenerator.CreateInterfaceProxyWithTargetInterface(@interface, interceptors));
        }
 // CreateInterfaceProxyWithTarget uses composition-based proxying to wrap a target object with
 // a proxy object implementing the desired interface. Calls are passed to the target object
 // after running interceptors. This model is similar to DispatchProxy.
 public static object Decorate(Type interfaceType, object target)
 => Generator.CreateInterfaceProxyWithTargetInterface(interfaceType, target, new DynamicProxyLoggingInterceptor(interfaceType.Name));
Ejemplo n.º 19
0
    public static void RewireWithAspects(this IServiceCollection services, Action <IAspectOptions>?options = null)
    {
        var aspectRegistry = new AspectRegistry();

        services.AddSingleton(aspectRegistry);

        var optionsBuilder = new AspectOptionsBuilder();

        options?.Invoke(optionsBuilder);

        foreach (var map in optionsBuilder.Maps)
        {
            aspectRegistry.RegisterAspectTrigger(map.Attribute, map.Aspect);
        }

        foreach (var aspectType in aspectRegistry.RegisteredAspectTypes)
        {
            services.AddTransient(aspectType);
        }

        var descriptorsOfAnnotatedServices = services
                                             .Where(IsSupportedServiceDescriptor)
                                             .Where(x => aspectRegistry.HasTriggers(x.ImplementationType !))
                                             .ToArray();

        foreach (var serviceDescriptor in descriptorsOfAnnotatedServices)
        {
            aspectRegistry.RegisterAnnotatedService(serviceDescriptor.ImplementationType !);
        }

        // remove current service registrations
        foreach (var serviceDescriptor in descriptorsOfAnnotatedServices)
        {
            services.Remove(serviceDescriptor);
        }

        // add service descriptor for implementation types
        foreach (var serviceDescriptor in descriptorsOfAnnotatedServices)
        {
            services.Add(ServiceDescriptor.Describe(
                             serviceType: serviceDescriptor.ImplementationType !,
                             implementationType: serviceDescriptor.ImplementationType !,
                             lifetime: serviceDescriptor.Lifetime
                             ));
        }

        // add new service descriptor with proxy factory
        foreach (var serviceDescriptor in descriptorsOfAnnotatedServices)
        {
            var implementationType = serviceDescriptor.ImplementationType !;
            var lifetime           = serviceDescriptor.Lifetime;
            var serviceType        = serviceDescriptor.ServiceType;

            services.Add(ServiceDescriptor.Describe(
                             serviceType: serviceType,
                             provider =>
            {
                var myClass     = provider.GetRequiredService(implementationType);
                var interceptor = new MethodInterceptor(new PipelineStepFactory(provider, aspectRegistry));

                return(_proxyGenerator.CreateInterfaceProxyWithTargetInterface(
                           interfaceToProxy: serviceType,
                           target: myClass,
                           new IAsyncInterceptor[] { interceptor }
                           ));
            },
                             lifetime
                             ));
        }
    }
Ejemplo n.º 20
0
    public static TSomething MakeSomething <TSomething>(TSomething instance) where TSomething : class
    {
        TSomething proxy = _generator.CreateInterfaceProxyWithTargetInterface <TSomething>(instance, new MyInterceptor());

        return(proxy);
    }
Ejemplo n.º 21
0
        public void LoadAssemblyIntoCache_InvalidCacheAfterTwoLoadAssemblyIntoCacheThatContainsSameGeneric()
        {
            //
            // Step 1 - Save an assembly with 1 generic proxy
            //
            var proxyGeneratorModuleScope = new ModuleScope(
                true,
                true,
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "1",
                "ProxyCache1.dll",
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "1",
                "ProxyCache1.dll"
                );
            var proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            var generator    = new ProxyGenerator(proxyBuilder);

            generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IGenericInterface <IInterface1>),
                new Class1(),
                new DoNothingInterceptor()
                );
            proxyGeneratorModuleScope.SaveAssembly();

            //
            // Step 2 - Save another assembly with 1 generic proxy
            // note : to reproduce the problem, must load previously saved assembly (in cache) before saving this assembly.
            //
            proxyGeneratorModuleScope = new ModuleScope(
                true,
                true,
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "2",
                "ProxyCache2.dll",
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "2",
                "ProxyCache2.dll"
                );
            proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            generator    = new ProxyGenerator(proxyBuilder);

            var proxyAssembly = Assembly.LoadFrom("ProxyCache1.dll");

            proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly);

            generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IGenericInterface <IInterface2>),
                new Class2(),
                new DoNothingInterceptor()
                );
            proxyGeneratorModuleScope.SaveAssembly();

            //
            // Step 3 - Load the last proxy assembly and try to create the first generic proxy (created in step 1)
            // note : Creating proxy from step 2 works.
            // exception : Missing method exception, it returns the wrong proxy and the constructor used doesn't match the arguments passed.
            //
            proxyGeneratorModuleScope = new ModuleScope(true);
            proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            generator    = new ProxyGenerator(proxyBuilder);

            proxyAssembly = Assembly.LoadFrom("ProxyCache2.dll");
            proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly);

            generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IGenericInterface <IInterface1>),
                new Class1(),
                new DoNothingInterceptor()
                );
        }
Ejemplo n.º 22
0
        public void LoadAssemblyIntoCache_InvalidCacheAfterTwoLoadAssemblyIntoCacheThatContainsSameInterface()
        {
            //
            // Step 1 - Save an assembly with 1 interface proxy
            //
            var proxyGeneratorModuleScope = new ModuleScope(
                true,
                true,
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "3",
                "ProxyCache3.dll",
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "3",
                "ProxyCache3.dll"
                );
            var proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            var generator    = new ProxyGenerator(proxyBuilder);

            generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IInterface3),
                new[] { typeof(IInterface2) },
                new Class3(),
                new DoNothingInterceptor()
                );
            proxyGeneratorModuleScope.SaveAssembly();

            //
            // Step 2 - Save another assembly with 1 interface proxy
            // note : to reproduce the problem, must load previously saved assembly (in cache) before saving this assembly.
            //
            proxyGeneratorModuleScope = new ModuleScope(
                true,
                true,
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "4",
                "ProxyCache4.dll",
                ModuleScope.DEFAULT_ASSEMBLY_NAME + "4",
                "ProxyCache4.dll"
                );
            proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            generator    = new ProxyGenerator(proxyBuilder);

            var proxyAssembly = Assembly.LoadFrom("ProxyCache3.dll");

            proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly);

            generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IInterface3),
                new[] { typeof(IInterface1) },
                new Class4(),
                new DoNothingInterceptor()
                );
            proxyGeneratorModuleScope.SaveAssembly();

            //
            // Step 3 - Load the last proxy assembly and try to create the first interface proxy (created in step 1)
            // note : Creating proxy from step 2 works.
            // issue : returns the wrong proxy (the one from step 2)
            //
            proxyGeneratorModuleScope = new ModuleScope(true);
            proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope);
            generator    = new ProxyGenerator(proxyBuilder);

            proxyAssembly = Assembly.LoadFrom("ProxyCache4.dll");
            proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly);

            var invalidProxy = generator.CreateInterfaceProxyWithTargetInterface(
                typeof(IInterface3),
                new[] { typeof(IInterface2) },
                new Class3(),
                new DoNothingInterceptor()
                );

            if (invalidProxy as IInterface2 == null)
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 23
0
    public IMyService Create()
    {
        IMyService proxy = _proxyGenerator.CreateInterfaceProxyWithTargetInterface <IMyService>(null, _interceptor);

        return(proxy);
    }