protected static void TestCreatedSimpleProxy(ISimpleInterface testClassProxy) { testClassProxy.Should().Not.Be.Null(); // No test for method 1, just make sure it doesn't bomb ;-) testClassProxy.Method1(); testClassProxy.Method2().Should().Be("Hello World!"); testClassProxy.Method3().Should().Be(10000); testClassProxy.Method4(123456).Should().Be(123456); int outValue = 1234; testClassProxy.Method5(3456, out outValue); outValue.Should().Be(3456); int refValue = 56748; testClassProxy.Method6(ref refValue); refValue.Should().Be(98765); // Test casting IImplemented implementedInterface = (IImplemented)testClassProxy; implementedInterface.Should().Not.Be.Null(); implementedInterface.ImplementedMethod(); // Test IDynamicProxy test IDynamicProxy dynProxy = (IDynamicProxy)testClassProxy; dynProxy.Should().Not.Be.Null(); }
//public object Create(IDynamicProxy handler, Type objType, bool isObjInterface) { public object Create(IDynamicProxy handler, Type objType, Type[] aditionalInterfaces = null) { string typeName = objType.FullName + PROXY_SUFFIX; Type type = typeMap[typeName] as Type; // Verifica se o tipo já existe no cache de tipos criados dinamicamente. Caso não exista, cria a nova instancia e adiciona ao cache. if (type == null) { List <Type> interfacesToImplement = new List <Type>(); // Verifica se foram especificadas interfaces adicionais. if (aditionalInterfaces != null && aditionalInterfaces.Any() == true) { interfacesToImplement.AddRange(aditionalInterfaces); } if (objType.IsInterface == true) { // Pega todas as interfaces que são herdadas. Type[] baseInterfaces = objType.GetInterfaces(); if (baseInterfaces != null) { // Adiciona cada interface herdada na lista de interfaces a serem implementadas. for (int i = 0; i < baseInterfaces.Length; i++) { interfacesToImplement.Add(baseInterfaces[i]); } } interfacesToImplement.Add(objType); } else { interfacesToImplement.AddRange(objType.GetInterfaces()); } // Verifica se foram encontradas interfaces a serem implementadas. if (interfacesToImplement == null || interfacesToImplement.Any() == false) { throw new ArgumentException(objType.FullName + " has no interfaces to implement", "objType"); } type = CreateType(handler, interfacesToImplement.ToArray(), typeName); Type existingType = typeMap[typeName] as Type; if (existingType == null) { typeMap.Add(typeName, type); } } // Retorna uma nova instancia do tipo. return(Activator.CreateInstance(type, new object[] { handler })); }
protected ProxyObjectReference(SerializationInfo info, StreamingContext context) { string typeName = info.GetString("__baseType"); _baseType = Type.GetType(typeName, true, false); var baseInterfaces = new List<Type>(); int count = info.GetInt32("__baseInterfaceCount"); for (int index = 0; index < count; index++) { string name = string.Format("__baseInterface{0}", index); baseInterfaces.Add(Type.GetType(info.GetString(name), true, false)); } var proxyType = new DynamicProxyBuilder().CreateProxiedType(_baseType, baseInterfaces.ToArray()); _proxy = (IDynamicProxy)Activator.CreateInstance(proxyType, new object[] { info, context }); }
//public object Create(IDynamicProxy handler, Type objType, bool isObjInterface) { public object Create(IDynamicProxy handler, Type objType, Type[] aditionalInterfaces = null) { string typeName = objType.FullName + PROXY_SUFFIX; Type type = typeMap[typeName] as Type; // Verifica se o tipo já existe no cache de tipos criados dinamicamente. Caso não exista, cria a nova instancia e adiciona ao cache. if (type == null) { List<Type> interfacesToImplement = new List<Type>(); // Verifica se foram especificadas interfaces adicionais. if (aditionalInterfaces != null && aditionalInterfaces.Any() == true) { interfacesToImplement.AddRange(aditionalInterfaces); } if (objType.IsInterface == true) { // Pega todas as interfaces que são herdadas. Type[] baseInterfaces = objType.GetInterfaces(); if (baseInterfaces != null) { // Adiciona cada interface herdada na lista de interfaces a serem implementadas. for (int i = 0; i < baseInterfaces.Length; i++) { interfacesToImplement.Add(baseInterfaces[i]); } } interfacesToImplement.Add(objType); } else { interfacesToImplement.AddRange(objType.GetInterfaces()); } // Verifica se foram encontradas interfaces a serem implementadas. if (interfacesToImplement == null || interfacesToImplement.Any() == false) { throw new ArgumentException(objType.FullName + " has no interfaces to implement", "objType"); } type = CreateType(handler, interfacesToImplement.ToArray(), typeName); Type existingType = typeMap[typeName] as Type; if (existingType == null) { typeMap.Add(typeName, type); } } // Retorna uma nova instancia do tipo. return Activator.CreateInstance(type, new object[] { handler }); }
protected ProxyObjectReference(SerializationInfo info, StreamingContext context) { string typeName = info.GetString("__baseType"); _baseType = Type.GetType(typeName, true, false); var baseInterfaces = new List <Type>(); int count = info.GetInt32("__baseInterfaceCount"); for (int index = 0; index < count; index++) { string name = string.Format("__baseInterface{0}", index); baseInterfaces.Add(Type.GetType(info.GetString(name), true, false)); } var proxyType = new DynamicProxyBuilder().CreateProxiedType(_baseType, baseInterfaces.ToArray()); _proxy = (IDynamicProxy)Activator.CreateInstance(proxyType, new object[] { info, context }); }
public virtual object GetProxy() { IDynamicProxy proxy = CreateAopProxy(); return(proxy.GetProxy()); }
public void RemoveInactiveProxy(IDynamicProxy inactiveProxy) { _ActiveProxies.Remove(inactiveProxy); CheckActiveProxy(); }
public void AddActiveProxy(IDynamicProxy activeProxy) { _ActiveProxies.Add(activeProxy); CheckActiveProxy(); }
private Type CreateType(IDynamicProxy handler, Type[] interfaces, string dynamicTypeName) { Type retVal = null; if (handler != null && interfaces != null) { Type objType = typeof(System.Object); Type handlerType = typeof(IDynamicProxy); AppDomain domain = Thread.GetDomain(); AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = ASSEMBLY_NAME; assemblyName.Version = new Version(1, 0, 0, 0); // Cria um novo assembly para o proxy, que será executado apenas em memória. AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); // Cria um módulo para conter o proxy. ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME); // Define os atributos do proxy como public e sealed. TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed; // Define as informações do proxy para instanciar um TypeBuilder. O proxy deve herdar de object e das interfaces a serem implementadas. TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicTypeName, typeAttributes, objType, interfaces); // Criamos um campo que será utilizado como delegate para executar os métodos originais após a execução do proxy. FieldBuilder handlerField = typeBuilder.DefineField(HANDLER_NAME, handlerType, FieldAttributes.Private); // Constrói o construtor que recebe o delegate como argumento. ConstructorInfo superConstructor = objType.GetConstructor(new Type[0]); ConstructorBuilder delegateConstructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { handlerType }); #region( "Constructor IL Code" ) ILGenerator constructorIL = delegateConstructor.GetILGenerator(); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Load first constructor parameter constructorIL.Emit(OpCodes.Ldarg_1); // Set the first parameter into the handler field constructorIL.Emit(OpCodes.Stfld, handlerField); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Call the super constructor constructorIL.Emit(OpCodes.Call, superConstructor); // Constructor return constructorIL.Emit(OpCodes.Ret); #endregion // Para cada método definido nas interfaces, cria a implementação concreta no tipo dinâmico. foreach (Type interfaceType in interfaces) { GenerateMethod(interfaceType, handlerField, typeBuilder); } retVal = typeBuilder.CreateType(); } return retVal; }
private Type CreateType(IDynamicProxy handler, Type[] interfaces, string dynamicTypeName) { Type retVal = null; if (handler != null && interfaces != null) { Type objType = typeof(System.Object); Type handlerType = typeof(IDynamicProxy); AppDomain domain = Thread.GetDomain(); AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = ASSEMBLY_NAME; assemblyName.Version = new Version(1, 0, 0, 0); // Cria um novo assembly para o proxy, que será executado apenas em memória. AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); // Cria um módulo para conter o proxy. ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME); // Define os atributos do proxy como public e sealed. TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed; // Define as informações do proxy para instanciar um TypeBuilder. O proxy deve herdar de object e das interfaces a serem implementadas. TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicTypeName, typeAttributes, objType, interfaces); // Criamos um campo que será utilizado como delegate para executar os métodos originais após a execução do proxy. FieldBuilder handlerField = typeBuilder.DefineField(HANDLER_NAME, handlerType, FieldAttributes.Private); // Constrói o construtor que recebe o delegate como argumento. ConstructorInfo superConstructor = objType.GetConstructor(new Type[0]); ConstructorBuilder delegateConstructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { handlerType }); #region ( "Constructor IL Code" ) ILGenerator constructorIL = delegateConstructor.GetILGenerator(); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Load first constructor parameter constructorIL.Emit(OpCodes.Ldarg_1); // Set the first parameter into the handler field constructorIL.Emit(OpCodes.Stfld, handlerField); // Load "this" constructorIL.Emit(OpCodes.Ldarg_0); // Call the super constructor constructorIL.Emit(OpCodes.Call, superConstructor); // Constructor return constructorIL.Emit(OpCodes.Ret); #endregion // Para cada método definido nas interfaces, cria a implementação concreta no tipo dinâmico. foreach (Type interfaceType in interfaces) { GenerateMethod(interfaceType, handlerField, typeBuilder); } retVal = typeBuilder.CreateType(); } return(retVal); }