public void WhenCallingServiceThrowingExceptionThenInterceptorIsCalled() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); var proxy = builder.Build(service, this.interceptor.Object); bool exceptionRaised = false; // Act try { proxy.ThrowsException(); } catch (Exception) { exceptionRaised = true; } // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Once()); this.interceptor.Verify(i => i.OnExecuted(), Times.Never()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Once()); Assert.True(exceptionRaised); }
public void WhenBuildingWithoutServiceThenThrowsArgumentNullException() { // Assign DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); bool exceptionRaised = false; // Act try { builder.Build <SimpleService>(null, this.interceptor.Object); } catch (ArgumentNullException) { exceptionRaised = true; } // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Never()); this.interceptor.Verify(i => i.OnExecuted(), Times.Never()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Never()); Assert.True(exceptionRaised); }
public static object CreateProxy(Type targetType, IRuntimeInterception[] runtimeInterceptionChain) { Type proxyType; object proxyInstance; object[] activationArgs; IProxyBuilder proxyBuilder; IInterceptor interceptor; if ((object)targetType == null) { throw new ArgumentNullException(nameof(targetType)); } if ((object)runtimeInterceptionChain == null) { throw new ArgumentNullException(nameof(runtimeInterceptionChain)); } proxyBuilder = new DefaultProxyBuilder(); proxyType = proxyBuilder.CreateInterfaceProxyTypeWithoutTarget(targetType, new Type[] { }, ProxyGenerationOptions.Default); interceptor = new CastleToSolderInterceptor(runtimeInterceptionChain); activationArgs = new object[] { new IInterceptor[] { interceptor }, new object() }; proxyInstance = Activator.CreateInstance(proxyType, activationArgs); return(proxyInstance); }
public void Issue215Test() { var container = new DependencyInjectionContainer(); var proxyType = new DefaultProxyBuilder().CreateClassProxyType( typeof(ExampleClass), new Type[0], ProxyGenerationOptions.Default); container.Configure(c => { c.ExportFactory <IExampleClassFactory>(); c.ExportDecorator(proxyType) .As(typeof(ExampleClass)) .WithCtorParam <IExportLocatorScope, IInterceptor[]>( scope => new IInterceptor[0]); }); var factory = container.Locate <IExampleClassFactory>(); var cancellationToken = new CancellationTokenSource(); var instance = factory.Create(1, 2, true, 3, 4, cancellationToken); Assert.NotNull(instance); Assert.Equal(1, instance.StartId); Assert.Equal(2, instance.EndId); Assert.True(instance.Reverse); Assert.Equal(3, instance.LoadIdsLimit); Assert.Equal(4, instance.MaxBufferSize); Assert.Same(cancellationToken, instance.CancellationTokenSource); Assert.NotNull(instance.Dependency1); Assert.NotNull(instance.Dependency2); }
/// <summary> /// Ensures that a service always resolves as lazy proxy (uses DefaultProxyBuilder). /// </summary> /// <param name="registrator">The registrator.</param> /// <param name="interfaceType">The type of the interface.</param> /// <param name="serviceKey">Optional service key.</param> public static IRegistrator ResolveAsLazyViaProxyBuilder(this IRegistrator registrator, Type interfaceType, object serviceKey = null) { // registration of lazy interceptor registrator.Register(typeof(LazyInterceptor <>), setup: Setup.Wrapper, ifAlreadyRegistered: IfAlreadyRegistered.Keep); // lazy proxy wrapper var proxyBuilder = new DefaultProxyBuilder(); var proxyType = proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(interfaceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default); // decorator for the generated proxy class var decoratorSetup = GetDecoratorSetup(serviceKey); // make typeof(LazyInterceptor<interfaceType>[]) var lazyInterceptorArrayType = typeof(LazyInterceptor <>).MakeGenericType(interfaceType).MakeArrayType(); // register the proxy class as decorator registrator.Register(interfaceType, proxyType, Reuse.Transient, setup: decoratorSetup, made: Made.Of(type => type.PublicConstructors().SingleOrDefault(ctor => ctor.GetParameters().Length != 0), Parameters.Of .Type(typeof(IInterceptor[]), lazyInterceptorArrayType) .Type(interfaceType, r => null))); return(registrator); }
public void CacheMappingsHoldTypes() { ModuleScope scope = new ModuleScope(true); DefaultProxyBuilder builder = new DefaultProxyBuilder(scope); Type cp = builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, ProxyGenerationOptions.Default); string savedPath = scope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args) { Assembly assembly = Assembly.LoadFrom((string)args[0]); CacheMappingsAttribute attribute = (CacheMappingsAttribute) assembly.GetCustomAttributes(typeof(CacheMappingsAttribute), false)[0]; Dictionary <CacheKey, string> entries = attribute.GetDeserializedMappings(); Assert.AreEqual(1, entries.Count); CacheKey key = new CacheKey(typeof(object), new Type[0], ProxyGenerationOptions.Default); Assert.IsTrue(entries.ContainsKey(key)); Assert.AreEqual(args[1], entries[key]); }, savedPath, cp.FullName); File.Delete(savedPath); }
private object CreateDataAccessObject(Type type) { try { string xmlTemplete = "<sqlMap embedded=\"{0},{1}\" xmlns=\"http://ibatis.apache.org/dataMapper\" />"; XmlDocument config = new XmlDocument(); config.LoadXml(string.Format(xmlTemplete, type.FullName + ".sql.xml", type.Assembly.FullName)); if (this._context.Reader != null) { _mapLoader.ReadOnlyBuilder.ConfigureSqlMap(config.DocumentElement); } _mapLoader.WriteBuilder.ConfigureSqlMap(config.DocumentElement); } catch (Exception ex) { throw new DataAccessException(string.Format("创建数据访问对象失败,对象类型:{0}", type.FullName), ex); } DefaultProxyBuilder builder = new DefaultProxyBuilder(); ProxyGenerator generator = new ProxyGenerator(builder); DataAccessOutSqlTextConfig outTypeConfig = null; var outSqlType = type.GetCustomAttribute <DataAccessOutSqlTextAttribute>(); if (outSqlType != null) { outTypeConfig = outSqlType.Create(); } return(generator.CreateInterfaceProxyWithoutTarget(type, new DataAccess(this._context, outTypeConfig))); }
public void DefaultProxyBuilderWithSpecificScope() { var scope = new ModuleScope(false); var builder = new DefaultProxyBuilder(scope); Assert.AreSame(scope, builder.ModuleScope); }
public static Type GetTypeKey() { var moduleScope = new ModuleScope(false, false, NamingScope, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME); var proxyBuilder = new DefaultProxyBuilder(moduleScope); return(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ISupportKeyedService), null, ProxyGenerationOptions)); }
public void WhenBuildingWithoutParameterlessCtorServiceThenThrowsNotSupportedException() { // Assign BadService service = new BadService("test"); DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); bool exceptionRaised = false; // Act try { builder.Build(service, this.interceptor.Object); } catch (NotSupportedException) { exceptionRaised = true; } // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Never()); this.interceptor.Verify(i => i.OnExecuted(), Times.Never()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Never()); Assert.True(exceptionRaised); }
private void CheckLoadAssemblyIntoCache(ProxyCreator creator) { var savedScope = new ModuleScope(true); var builder = new DefaultProxyBuilder(savedScope); var cp = creator(builder); Assert.AreSame(cp, creator(builder)); var path = savedScope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain( delegate(object[] args) { var newScope = new ModuleScope(false); var newBuilder = new DefaultProxyBuilder(newScope); var assembly = Assembly.LoadFrom((string)args[0]); newScope.LoadAssemblyIntoCache(assembly); var loadedCP = assembly.GetType((string)args[1]); Assert.AreSame(loadedCP, ((ProxyCreator)args[2])(newBuilder)); Assert.AreEqual(assembly, ((ProxyCreator)args[2])(newBuilder).Assembly); }, path, cp.FullName, creator ); File.Delete(path); }
public static ProxyGenerator GetProxyFull() { String path = AppDomain.CurrentDomain.BaseDirectory; ModuleScope scope = new ModuleScope(true, true, "Invocation", path + "\\Invocation.dll", "Proxy", path + "\\Proxy.dll"); DefaultProxyBuilder builder = new DefaultProxyBuilder(scope); return(new ProxyGenerator(builder)); }
public StashboxContainerAdapter() { var builder = new DefaultProxyBuilder(); this.proxyType1 = builder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ICalculator1), new Type[0], ProxyGenerationOptions.Default); this.proxyType2 = builder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ICalculator2), new Type[0], ProxyGenerationOptions.Default); this.proxyType3 = builder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ICalculator3), new Type[0], ProxyGenerationOptions.Default); }
public void ConfigureContainer(IStashboxContainer container) { var proxyBuilder = new DefaultProxyBuilder(); container.Register <IInterceptor, NoInterceptor>(); container.RegisterDecorator <ILevel2Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2Service), Array.Empty <Type>(), ProxyGenerationOptions.Default)); container.RegisterDecorator <ILevel2bService>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2bService), Array.Empty <Type>(), ProxyGenerationOptions.Default)); container.RegisterDecorator <ILevel3Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel3Service), Array.Empty <Type>(), ProxyGenerationOptions.Default)); }
public void LoadAssemblyIntoCache_DifferentGenerationOptions() { var savedScope = new ModuleScope(true); var builder = new DefaultProxyBuilder(savedScope); var options1 = new ProxyGenerationOptions(); options1.AddMixinInstance(new DateTime()); var options2 = ProxyGenerationOptions.Default; var cp1 = builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options1); var cp2 = builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options2); Assert.AreNotSame(cp1, cp2); Assert.AreSame( cp1, builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options1) ); Assert.AreSame( cp2, builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options2) ); var path = savedScope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain( delegate(object[] args) { var newScope = new ModuleScope(false); var newBuilder = new DefaultProxyBuilder(newScope); var assembly = Assembly.LoadFrom((string)args[0]); newScope.LoadAssemblyIntoCache(assembly); var newOptions1 = new ProxyGenerationOptions(); newOptions1.AddMixinInstance(new DateTime()); var newOptions2 = ProxyGenerationOptions.Default; var loadedCP1 = newBuilder.CreateClassProxyType( typeof(object), Type.EmptyTypes, newOptions1 ); var loadedCP2 = newBuilder.CreateClassProxyType( typeof(object), Type.EmptyTypes, newOptions2 ); Assert.AreNotSame(loadedCP1, loadedCP2); Assert.AreEqual(assembly, loadedCP1.Assembly); Assert.AreEqual(assembly, loadedCP2.Assembly); }, path ); File.Delete(path); }
/// <summary> /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method. /// </summary> /// <param name="assembly">Assembly to register</param> /// <param name="config">Additional configuration</param> public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config) { var context = new ConventionalRegistrationContext(assembly, this, config); foreach (var registerer in _conventionalRegistrars) { registerer.RegisterAssembly(context); } if (config.InstallInstallers) { this.Install(assembly); } // 这里使用 TPL 并行库的原因是因为存在大量仓储类型与应用服务需要注册,应最大限度利用 CPU 来进行操作 Parallel.ForEach(_waitRegisterInterceptor, keyValue => { var proxyBuilder = new DefaultProxyBuilder(); Type proxyType; if (keyValue.Key.IsInterface) { proxyType = proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(keyValue.Key, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default); } else if (keyValue.Key.IsClass()) { proxyType = proxyBuilder.CreateClassProxyTypeWithTarget(keyValue.Key, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default); } else { throw new ArgumentException($"类型 {keyValue.Value} 不支持进行拦截器服务集成。"); } var decoratorSetup = Setup.DecoratorWith(useDecorateeReuse: true); // 使用 ProxyBuilder 创建好的代理类替换原有类型的实现 IocContainer.Register(keyValue.Key, proxyType, made: Made.Of(type => type.GetConstructors().SingleOrDefault(c => c.GetParameters().Length != 0), Parameters.Of.Type <IInterceptor[]>(request => { var objects = new List <object>(); foreach (var interceptor in keyValue.Value) { objects.Add(request.Container.Resolve(interceptor)); } return(objects.Cast <IInterceptor>().ToArray()); }), PropertiesAndFields.Auto), setup: decoratorSetup); }); _waitRegisterInterceptor.Clear(); }
public void WhenBuildingProxyThenReturnsProxyOfSameType() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); // Act var proxy = builder.Build(service, this.interceptor.Object); // Assert Assert.NotNull(proxy); Assert.IsAssignableFrom(typeof(SimpleService), proxy); }
public ProxyFactory() { ModuleScope scope; #if !SILVERLIGHT scope = new ModuleScope(false, false, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME, "De.Osthus.Ambeth.Proxy", "De.Osthus.Ambeth.Proxy.Transfer"); #else scope = new ModuleScope(false, ModuleScope.DEFAULT_ASSEMBLY_NAME, ModuleScope.DEFAULT_FILE_NAME, "De.Osthus.Ambeth.Proxy", "De.Osthus.Ambeth.Proxy.Transfer"); #endif IProxyBuilder builder = new DefaultProxyBuilder(scope); proxyGenerator = new ProxyGenerator(builder); ProxyOptionsFactory = new DefaultProxyOptionsFactory(); }
/// <summary> /// Creates an instance of T where all methods marked with [Once] are only executed once. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Once <T>(Action <T> initializer) { var builder = new DefaultProxyBuilder(); var generator = new ProxyGenerator(builder); var onceInterceptor = new OnceInterceptor(); var onceProxy = generator.CreateClassProxy(typeof(T), new ProxyGenerationOptions { Hook = new OnceHook() }, onceInterceptor); var proxy = (T)onceProxy; initializer(proxy); return(proxy); }
public void WhenBuildingProxyMultipleTimesThenUseCache() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); // Act builder.Build(service, this.interceptor.Object); var proxy = builder.Build(service, this.interceptor.Object); // Assert // TODO : How to validate the cache hit? Using a external object? Assert.NotNull(proxy); Assert.IsAssignableFrom(typeof(SimpleService), proxy); }
public void Ensure_Expression_Override_Does_Not_Mess_Up_Cache() { var proxyBuilder = new DefaultProxyBuilder(); using var container = new StashboxContainer().Register <IInterceptor, NoInterceptor>() .RegisterDecorator <ILevel2Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2Service), new Type[0], ProxyGenerationOptions.Default)) .RegisterDecorator <ILevel2bService>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2bService), new Type[0], ProxyGenerationOptions.Default)) .RegisterDecorator <ILevel3Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel3Service), new Type[0], ProxyGenerationOptions.Default)) .RegisterScoped <ILevel1Service, Level1Service>() .RegisterScoped <ILevel2Service, Level2Service>() .RegisterScoped <ILevel2bService, Level2bService>() .RegisterScoped <ILevel3Service, Level3Service>() .RegisterScoped <ILevel4Service, Level4Service>(); Assert.NotNull(container.Resolve <ILevel2Service>()); }
public void LoadAssemblyIntoCache_InvalidCacheAfterTwoLoadAssemblyIntoCacheThatContainsSameClass() { // // Step 1 - Save an assembly with 1 class proxy // var proxyGeneratorModuleScope = new ModuleScope(true, true, ModuleScope.DEFAULT_ASSEMBLY_NAME + "5", "ProxyCache5.dll", ModuleScope.DEFAULT_ASSEMBLY_NAME + "5", "ProxyCache5.dll"); var proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope); var generator = new ProxyGenerator(proxyBuilder); generator.CreateClassProxy(typeof(EmptyClass), new[] { typeof(IInterface1) }, new DoNothingInterceptor()); proxyGeneratorModuleScope.SaveAssembly(); // // Step 2 - Save another assembly with 1 class 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 + "6", "ProxyCache6.dll", ModuleScope.DEFAULT_ASSEMBLY_NAME + "6", "ProxyCache6.dll"); proxyBuilder = new DefaultProxyBuilder(proxyGeneratorModuleScope); generator = new ProxyGenerator(proxyBuilder); var proxyAssembly = Assembly.LoadFrom("ProxyCache5.dll"); proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly); generator.CreateClassProxy(typeof(EmptyClass), new[] { typeof(IInterface2) }, new DoNothingInterceptor()); proxyGeneratorModuleScope.SaveAssembly(); // // Step 3 - Load the last proxy assembly and try to create the first class 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("ProxyCache6.dll"); proxyGeneratorModuleScope.LoadAssemblyIntoCache(proxyAssembly); var invalidProxy = generator.CreateClassProxy(typeof(EmptyClass), new[] { typeof(IInterface1) }, new DoNothingInterceptor()); if (invalidProxy as IInterface1 == null) { Assert.Fail(); } }
private static ProxyGenerator CreateProxyGenerator() { #if !NETFX_CORE var builder = new DefaultProxyBuilder(); #else IProxyBuilder builder = null; if (MoqRTRuntime.IsBaking) { builder = new PersistentProxyBuilder(); } else { builder = new DefaultProxyBuilder(); } #endif return(new ProxyGenerator(builder)); }
// 8.导出、生成代理类型 public static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); string path = Directory.GetCurrentDirectory(); ModuleScope scope = new ModuleScope(true, false, "Invocation", Path.Combine(path, "invocation.dll"), "Proxy", Path.Combine(path, "Proxy.dll")); DefaultProxyBuilder builder = new DefaultProxyBuilder(scope); ProxyGenerator generator = new ProxyGenerator(builder); ILogger logger = generator.CreateClassProxy <Logger1>(new TestInterceptor2()); logger.Write("love"); //scope.SaveAssembly(true); //加这句话可以将动态生成的Invocation类保存到本地硬盘 //scope.SaveAssembly(false); //加这句话可以将动态生成的Proxy类保存到本地硬盘 Console.Read(); }
public void WhenCallingNonVirtualServiceThenInterceptorIsNotCalled() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); var proxy = builder.Build(service, this.interceptor.Object); // Act proxy.NonVirtual(); // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Never()); this.interceptor.Verify(i => i.OnExecuted(), Times.Never()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Never()); }
private static void Main(string[] args) { var container = new StashboxContainer(); container.RegisterScoped <ILevel1Service, Level1Service>(); container.RegisterScoped <ILevel2Service, Level2Service>(); container.RegisterScoped <ILevel2bService, Level2bService>(); container.RegisterScoped <ILevel3Service, Level3Service>(); container.RegisterScoped <ILevel4Service, Level4Service>(); var proxyBuilder = new DefaultProxyBuilder(); container.Register <IInterceptor, NoInterceptor>(); container.RegisterDecorator <ILevel1Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel1Service), Array.Empty <Type>(), ProxyGenerationOptions.Default)); container.RegisterDecorator <ILevel2Service>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2Service), Array.Empty <Type>(), ProxyGenerationOptions.Default)); container.RegisterDecorator <ILevel2bService>(proxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(typeof(ILevel2bService), Array.Empty <Type>(), ProxyGenerationOptions.Default)); var tmp = container.GetRequiredService <ILevel1Service>(); }
private ProxyGenerator CreateProxyGenerator(string proxyAssemblyName, string proxyAssemblyPath) { var strongAssemblyName = proxyAssemblyName; var strongModulePath = proxyAssemblyPath; var weakAssemblyName = ModuleScope.DEFAULT_ASSEMBLY_NAME; var weakModulePath = ModuleScope.DEFAULT_FILE_NAME; _scope = new ModuleScope( true, false, strongAssemblyName, strongModulePath, weakAssemblyName, weakModulePath ); var builder = new DefaultProxyBuilder(_scope); return(new ProxyGenerator(builder)); }
public void WhenCallingWithEnumParameterThenInterceptorIsCalled() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); var proxy = builder.Build(service, this.interceptor.Object); var value = StringSplitOptions.None; // Act proxy.EnumTypeParameter(value); // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Once()); this.interceptor.Verify(i => i.OnExecuted(), Times.Once()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Never()); }
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 doesnt 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()); }
public void WhenCallingServiceReturningEnumTypeThenInterceptorIsCalled() { // Assign SimpleService service = new SimpleService(); DefaultProxyBuilder builder = this.CreateTestableBuilder(); this.interceptor.Setup(i => i.OnExecuting()); this.interceptor.Setup(i => i.OnExecuted()); this.interceptor.Setup(i => i.OnException(It.IsAny <Exception>())); var proxy = builder.Build(service, this.interceptor.Object); // Act var value4 = proxy.ReturnsEnum(); // Assert this.interceptor.Verify(i => i.OnExecuting(), Times.Once()); this.interceptor.Verify(i => i.OnExecuted(), Times.Once()); this.interceptor.Verify(i => i.OnException(It.IsAny <Exception>()), Times.Never()); Assert.Equal(service.EnumValue, value4); }
private void CheckLoadAssemblyIntoCache(ProxyCreator creator) { var savedScope = new ModuleScope(true); var builder = new DefaultProxyBuilder(savedScope); var cp = creator(builder); Assert.AreSame(cp, creator(builder)); var path = savedScope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args) { var newScope = new ModuleScope(false); var newBuilder = new DefaultProxyBuilder(newScope); var assembly = Assembly.LoadFrom((string) args[0]); newScope.LoadAssemblyIntoCache(assembly); var loadedCP = assembly.GetType((string) args[1]); Assert.AreSame(loadedCP, ((ProxyCreator) args[2])(newBuilder)); Assert.AreEqual(assembly, ((ProxyCreator) args[2])(newBuilder).Assembly); }, path, cp.FullName, creator); File.Delete(path); }
public void LoadAssemblyIntoCache_DifferentGenerationOptions() { var savedScope = new ModuleScope(true); var builder = new DefaultProxyBuilder(savedScope); var options1 = new ProxyGenerationOptions(); options1.AddMixinInstance(new DateTime()); var options2 = ProxyGenerationOptions.Default; var cp1 = builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options1); var cp2 = builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options2); Assert.AreNotSame(cp1, cp2); Assert.AreSame(cp1, builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options1)); Assert.AreSame(cp2, builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options2)); var path = savedScope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args) { var newScope = new ModuleScope(false); var newBuilder = new DefaultProxyBuilder(newScope); var assembly = Assembly.LoadFrom((string) args[0]); newScope.LoadAssemblyIntoCache(assembly); var newOptions1 = new ProxyGenerationOptions(); newOptions1.AddMixinInstance(new DateTime()); var newOptions2 = ProxyGenerationOptions.Default; var loadedCP1 = newBuilder.CreateClassProxyType(typeof (object), Type.EmptyTypes, newOptions1); var loadedCP2 = newBuilder.CreateClassProxyType(typeof (object), Type.EmptyTypes, newOptions2); Assert.AreNotSame(loadedCP1, loadedCP2); Assert.AreEqual(assembly, loadedCP1.Assembly); Assert.AreEqual(assembly, loadedCP2.Assembly); }, path); File.Delete(path); }
public void CacheMappingsHoldTypes() { var scope = new ModuleScope(true); var builder = new DefaultProxyBuilder(scope); var cp = builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, ProxyGenerationOptions.Default); var savedPath = scope.SaveAssembly(); CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args) { var assembly = Assembly.LoadFrom((string) args[0]); var attribute = (CacheMappingsAttribute) assembly.GetCustomAttributes(typeof (CacheMappingsAttribute), false)[0]; var entries = attribute.GetDeserializedMappings(); Assert.AreEqual(1, entries.Count); var key = new CacheKey(typeof (object), new Type[0], ProxyGenerationOptions.Default); Assert.IsTrue(entries.ContainsKey(key)); Assert.AreEqual(args[1], entries[key]); }, savedPath, cp.FullName); File.Delete(savedPath); }