Example #1
0
        public object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface)
        {
            string typeName = objType.FullName + ProxySuffix;
            Type?  type     = null;

            lock (_typeMap)
            {
                _ = _typeMap.TryGetValue(typeName, out type);
            }

            // check to see if the type was in the cache.  If the type was not cached, then
            // create a new instance of the dynamic type and add it to the cache.
            if (type == null)
            {
                if (isObjInterface)
                {
                    type = CreateType(handler, new Type[] { objType }, typeName);
                }
                else
                {
                    type = CreateType(handler, objType.GetInterfaces(), typeName);
                }

                lock (_typeMap)
                {
                    _typeMap.Add(typeName, type);
                }
            }

            // return a new instance of the type.
            return(Activator.CreateInstance(type, new object[] { handler }) !);
        }
Example #2
0
 public TImplementationType Create <TImplementationType>(
     IProxyInvocationHandler handler,
     params object[] args)
     where TImplementationType : class
 {
     return(Create <TImplementationType, TImplementationType>(
                handler,
                ProxyType.Inheritance,
                args));
 }
Example #3
0
        private Type BuildInheritanceProxyType <TImplementationType>(
            IProxyInvocationHandler handler,
            string dynamicTypeName,
            Type[] constructorParamTypes)
            where TImplementationType : class
        {
            var moduleBuilder = DefineDynamicModule();

            var handlerType = typeof(IProxyInvocationHandler);
            var baseType    = typeof(TImplementationType);

            var typeBuilder = moduleBuilder.DefineType(
                dynamicTypeName,
                TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed,
                baseType);

            var handlerField = typeBuilder.DefineField(HandlerName, handlerType, FieldAttributes.Private);

            var superConstructor = baseType.GetConstructor(constructorParamTypes);

            var constructorParamterTypes = superConstructor
                                           .GetParameters()
                                           .Select(cp => cp.ParameterType)
                                           .Prepend(handlerType)
                                           .ToArray();

            var delegateConstructor = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                constructorParamterTypes);

            var constructorIL = delegateConstructor.GetILGenerator();

            constructorIL.Emit(OpCodes.Ldarg_0);

            // Load constructor paramters with offset of 2
            // Ldarg_S 0 = this (ie Ldarg_0)
            // Ldarg_S 1 = IProxyInvocationHandler<T>
            // From Ldarg_S 2 constructor paramters for base class
            for (var j = 0; j < constructorParamterTypes.Length - 1; j++)
            {
                constructorIL.Emit(OpCodes.Ldarg_S, j + 2);
            }

            constructorIL.Emit(OpCodes.Call, superConstructor);

            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Ldarg_1);
            constructorIL.Emit(OpCodes.Stfld, handlerField);
            constructorIL.Emit(OpCodes.Ret);

            GenerateInheritedMethods <TImplementationType>(baseType, handlerField, typeBuilder);

            return(typeBuilder.CreateType());
        }
 /// <summary>
 /// 创建一个代理对象
 /// </summary>
 /// <param name="handler"></param>
 /// <param name="objType"></param>
 /// <param name="isObjInterface"></param>
 /// <returns></returns>
 public Object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface)
 {
     if (isObjInterface)
     {
         return DynamicProxy.NewInstance(AppDomain.CurrentDomain, new Type[] { objType }, handler);
     }
     else
     {
         return DynamicProxy.NewInstance(AppDomain.CurrentDomain, objType.GetInterfaces(), handler);
     }
 }
Example #5
0
 /// <summary>
 /// 创建一个代理对象
 /// </summary>
 /// <param name="handler"></param>
 /// <param name="objType"></param>
 /// <param name="isObjInterface"></param>
 /// <returns></returns>
 public Object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface)
 {
     if (isObjInterface)
     {
         return(DynamicProxy.NewInstance(AppDomain.CurrentDomain, new Type[] { objType }, handler));
     }
     else
     {
         return(DynamicProxy.NewInstance(AppDomain.CurrentDomain, objType.GetInterfaces(), handler));
     }
 }
Example #6
0
        public TBaseType Create <TImplementationType, TBaseType>(
            IProxyInvocationHandler handler,
            ProxyType proxyType,
            params object[] args)
            where TImplementationType : class, TBaseType
            where TBaseType : class
        {
            if (handler is null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            var objectType = typeof(TImplementationType);
            var typeName   = $"{objectType.FullName}{ProxySuffix}";

            if (!typeMap.TryGetValue(typeName, out var type))
            {
                type = BuildType <TImplementationType, TBaseType>(
                    handler,
                    proxyType,
                    objectType,
                    typeName,
                    args);

                typeMap.TryAdd(typeName, type);
            }

            switch (proxyType)
            {
            case ProxyType.Inheritance:
                args = args
                       .Prepend(handler)
                       .ToArray();
                break;

            case ProxyType.Interfaces:
                args = args
                       .Prepend(Activator.CreateInstance(typeof(TImplementationType), args))
                       .Prepend(handler)
                       .ToArray();
                break;
            }

            return((TBaseType)Activator.CreateInstance(type, args));
        }
Example #7
0
        private Object _Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface = false)
        {
            string typeName = objType.FullName + PROXY_SUFFIX;

            // check to see if the type was in the cache.  If the type was not cached, then
            // create a new instance of the dynamic type and add it to the cache.
            if (!typeMap.ContainsKey(typeName))
            {
                Type[] interfaces = isObjInterface? new Type[] { objType }: objType.GetInterfaces();
                Type   _type      = CreateType(handler, interfaces, typeName);
                typeMap.Add(typeName, _type);
            }

            Type type = typeMap[typeName];

            // return a new instance of the type.
            return(Activator.CreateInstance(type, new object[] { handler }));
        }
Example #8
0
        public Object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface)
        {
            string typeName = objType.FullName + PROXY_SUFFIX;
            Type   type     = (Type)typeMap[typeName];

            // check to see if the type was in the cache.  If the type was not cached, then
            // create a new instance of the dynamic type and add it to the cache.
            if (type != null)
            {
                return(Activator.CreateInstance(type, new object[] { handler }));
            }
            type = CreateType(handler, isObjInterface ? new Type[] { objType } : objType.GetInterfaces(), typeName);

            typeMap.Add(typeName, type);

            // return a new instance of the type.
            return(Activator.CreateInstance(type, new object[] { handler }));
        }
        public Object Create( IProxyInvocationHandler handler, Type objType, bool isObjInterface )
        {
            string typeName = objType.FullName + PROXY_SUFFIX;
            Type type = (Type)typeMap[ typeName ];

            // check to see if the type was in the cache.  If the type was not cached, then
            // create a new instance of the dynamic type and add it to the cache.
            if ( type == null ) {
                if ( isObjInterface ) {
                    type = CreateType( handler, new Type[] { objType }, typeName );
                } else {
                    type = CreateType( handler, objType.GetInterfaces(), typeName );
                }

                typeMap.Add( typeName, type );
            }

            // return a new instance of the type.
            return Activator.CreateInstance( type, new object[] { handler } );
        }
        public Object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface)
        {
            string typeName = objType.FullName + PROXY_SUFFIX;
            Type type = (Type)typeMap[typeName];

            if (type == null)
            {
                if (isObjInterface)
                {
                    type = CreateType(handler, new Type[] { objType }, typeName);
                }
                else
                {
                    type = CreateType(handler, objType.GetInterfaces(), typeName);
                }

                typeMap.Add(typeName, type);
            }

            return Activator.CreateInstance(type, new object[] { handler });
        }
Example #11
0
        private Type BuildType <TImplementationType, TBaseType>(
            IProxyInvocationHandler handler,
            ProxyType proxyType,
            Type objectType,
            string typeName,
            object[] args)
            where TImplementationType : class, TBaseType
            where TBaseType : class
        {
            if (proxyType == ProxyType.Inheritance && (objectType.IsSealed || objectType.IsInterface))
            {
                throw new NotSupportedException($"{objectType.Name} is sealed/ or is a interface");
            }

            var constructorParamTypes = (args.Length > 0) ? args
                                        .Select(o => o.GetType())
                                        .ToArray() : new Type[0];

            if (objectType.GetConstructor(constructorParamTypes) is null)
            {
                throw new NotSupportedException($"{objectType.Name} has no matching constructor");
            }

            switch (proxyType)
            {
            case ProxyType.Inheritance:
                return(BuildInheritanceProxyType <TImplementationType>(
                           handler,
                           typeName,
                           constructorParamTypes));

            case ProxyType.Interfaces:
                return(BuildInterfacesProxyType <TImplementationType>(handler, typeName));

            default:
                return(null);
            }
        }
Example #12
0
        private Type CreateType(IProxyInvocationHandler handler, Type[] interfaces, string dynamicTypeName)
        {
            Type retVal = null;

            if (handler != null && interfaces != null)
            {
                Type objType     = typeof(System.Object);
                Type handlerType = typeof(IProxyInvocationHandler);

                AppDomain    domain       = Thread.GetDomain();
                AssemblyName assemblyName = new AssemblyName();
                assemblyName.Name    = ASSEMBLY_NAME;
                assemblyName.Version = new Version(1, 0, 0, 0);

                // create a new assembly for this proxy, one that isn't presisted on the file system
                AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

                // create a new module for this proxy
                ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME);

                // Set the class to be public and sealed
                TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;

                // Gather up the proxy information and create a new type builder.  One that
                // inherits from Object and implements the interface passed in
                TypeBuilder typeBuilder = moduleBuilder.DefineType(
                    dynamicTypeName, typeAttributes, objType, interfaces);

                // Define a member variable to hold the delegate
                FieldBuilder handlerField = typeBuilder.DefineField(
                    HANDLER_NAME, handlerType, FieldAttributes.Private);


                // build a constructor that takes the delegate object as the only argument
                // ConstructorInfo defaultObjConstructor = objType.GetConstructor( new Type[0] );
                ConstructorInfo    superConstructor    = objType.GetConstructor(new Type[0]);
                ConstructorBuilder delegateConstructor = typeBuilder.DefineConstructor(
                    MethodAttributes.Public, CallingConventions.Standard, new Type[] { handlerType });

                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);

                // for every method that the interfaces define, build a corresponding method in the dynamic type that calls the handlers invoke method.
                foreach (Type interfaceType in interfaces)
                {
                    this.GenerateMethod(interfaceType, handlerField, typeBuilder);
                }

                retVal = typeBuilder.CreateTypeInfo();
            }

            return(retVal);
        }
Example #13
0
 public static Object Create(IProxyInvocationHandler handler, Type objType, bool isObjInterface = false)
 {
     return(instance._Create(handler, objType, isObjInterface));
 }
Example #14
0
 public Object Create(IProxyInvocationHandler handler, Type objType)
 {
     return(Create(handler, objType, false));
 }
Example #15
0
 protected DynamicProxy(IProxyInvocationHandler handler)
 {
     this.handler = handler;
 }
Example #16
0
        private Type CreateType(IProxyInvocationHandler handler, Type[] interfaces, string dynamicTypeName)
        {
            Type objType     = typeof(object);
            Type handlerType = typeof(IProxyInvocationHandler);

            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name    = AssemblyName;
            assemblyName.Version = new Version(1, 0, 0, 0);

            // create a new assembly for this proxy, one that isn't presisted on the file system
            AssemblyBuilder assemblyBuilder =
#if VNEXT
                AssemblyBuilder.DefineDynamicAssembly(
#else
                AppDomain.CurrentDomain.DefineDynamicAssembly(
#endif
                    assemblyName, AssemblyBuilderAccess.Run);

            // create a new module for this proxy
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(ModuleName);

            // Set the class to be public and sealed
            TypeAttributes typeAttributes =
                TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;

            // Gather up the proxy information and create a new type builder.  One that
            // inherits from Object and implements the interface passed in
            TypeBuilder typeBuilder = moduleBuilder.DefineType(
                dynamicTypeName, typeAttributes, objType, interfaces);

            // Define a member variable to hold the delegate
            FieldBuilder handlerField = typeBuilder.DefineField(
                HandlerName, handlerType, FieldAttributes.Private);

            // build a constructor that takes the delegate object as the only argument
            ConstructorInfo    baseConstructor     = objType.GetConstructor(Type.EmptyTypes) !;
            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, baseConstructor);
            // Constructor return
            constructorIL.Emit(OpCodes.Ret);
            #endregion

            // for every method that the interfaces define, build a corresponding
            // method in the dynamic type that calls the handlers invoke method.
            foreach (Type interfaceType in interfaces)
            {
                GenerateMethod(interfaceType, handlerField, typeBuilder);
            }

            return(typeBuilder.CreateType() !);
        }
Example #17
0
 public static Object NewInstance(AppDomain domain, Type[] interfaces, IProxyInvocationHandler handler)
 {
     return(GetProxy(domain, interfaces)
            .GetConstructor(Types_InvocationHandler)
            .Invoke(new Object[] { handler }));
 }
        private Type CreateType(IProxyInvocationHandler handler, Type[] interfaces, String dynamicTypeName)
        {
            Type retVal = null;

            if (handler != null && interfaces != null)
            {
                Type objType = typeof(System.Object);
                Type handlerType = typeof(IProxyInvocationHandler);

                AppDomain domain = Thread.GetDomain();
                AssemblyName assemblyName = new AssemblyName();
                assemblyName.Name = ASSEMBLY_NAME;
                assemblyName.Version = new Version(1, 0, 0, 0);

                AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(
                    assemblyName, AssemblyBuilderAccess.Run);

                ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME);

                TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;

                TypeBuilder typeBuilder = moduleBuilder.DefineType(dynamicTypeName, typeAttributes, objType, interfaces);

                FieldBuilder handlerField = typeBuilder.DefineField(HANDLER_NAME, handlerType, FieldAttributes.Private);

                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();

                constructorIL.Emit(OpCodes.Ldarg_0);
                constructorIL.Emit(OpCodes.Ldarg_1);
                constructorIL.Emit(OpCodes.Stfld, handlerField);
                constructorIL.Emit(OpCodes.Ldarg_0);
                constructorIL.Emit(OpCodes.Call, superConstructor);
                constructorIL.Emit(OpCodes.Ret);
                #endregion

                foreach (Type interfaceType in interfaces)
                {
                    GenerateMethod(interfaceType, handlerField, typeBuilder);
                }

                retVal = typeBuilder.CreateType();
            }

            return retVal;
        }
Example #19
0
        private Type BuildInterfacesProxyType <TImplementationType>(
            IProxyInvocationHandler handler,
            string dynamicTypeName)
            where TImplementationType : class
        {
            var moduleBuilder = DefineDynamicModule();

            var handlerType         = typeof(IProxyInvocationHandler);
            var objectReferenceType = typeof(TImplementationType);
            var baseType            = typeof(object);
            var interfaces          = objectReferenceType.GetInterfaces();

            var typeBuilder = moduleBuilder.DefineType(
                dynamicTypeName,
                TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed,
                baseType,
                interfaces);

            var handlerField = typeBuilder
                               .DefineField(HandlerName, handlerType, FieldAttributes.Private);

            var objectReferenceFeild = typeBuilder
                                       .DefineField(ObjectReferenceName, objectReferenceType, FieldAttributes.Private);

            var superConstructor = baseType.GetConstructor(new Type[0]);

            var constructorParamterTypes = new Type[]
            {
                handlerType,
                objectReferenceType
            };

            var delegateConstructor = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                constructorParamterTypes);

            var constructorIL = delegateConstructor.GetILGenerator();

            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Call, superConstructor);

            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Ldarg_1);
            constructorIL.Emit(OpCodes.Stfld, handlerField);


            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Ldarg_2);
            constructorIL.Emit(OpCodes.Stfld, objectReferenceFeild);

            constructorIL.Emit(OpCodes.Ret);

            foreach (var interfaceType in interfaces)
            {
                GenerateInterfaceMethods <TImplementationType>(
                    interfaceType,
                    handlerField,
                    objectReferenceFeild,
                    typeBuilder);
            }

            return(typeBuilder.CreateType());
        }
Example #20
0
 public Object Create(IProxyInvocationHandler handler, Type objType)
 {
     return Create(handler, objType, false);
 }
 protected DynamicProxy(IProxyInvocationHandler handler)
 {
     this.handler = handler;
 }
Example #22
0
        private Type CreateType(IProxyInvocationHandler handler, Type[] interfaces, string dynamicTypeName)
        {
            Type retVal = null;

            if (handler != null && interfaces != null)
            {
                Type objType = typeof(Object);
                Type handlerType = typeof(IProxyInvocationHandler);

                AppDomain domain = Thread.GetDomain();
                AssemblyName assemblyName = new AssemblyName();
                assemblyName.Name = ASSEMBLY_NAME;
                assemblyName.Version = new Version(1, 0, 0, 0);

                // create a new assembly for this proxy, one that isn't presisted on the file system
                AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(
                    assemblyName, AssemblyBuilderAccess.Run);
                    // assemblyName, AssemblyBuilderAccess.RunAndSave,".");  // to save it to the disk

                // create a new module for this proxy
                ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(MODULE_NAME);

                // Set the class to be public and sealed
                TypeAttributes typeAttributes =
                    TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;

                // Gather up the proxy information and create a new type builder.  One that
                // inherits from Object and implements the interface passed in
                TypeBuilder typeBuilder = moduleBuilder.DefineType(
                    dynamicTypeName, typeAttributes, objType, interfaces);

                // Define a member variable to hold the delegate
                FieldBuilder handlerField = typeBuilder.DefineField(
                    HANDLER_NAME, handlerType, FieldAttributes.Private);


                // build a constructor that takes the delegate object as the only argument
                //ConstructorInfo defaultObjConstructor = objType.GetConstructor( new Type[0] );
                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

                // for every method that the interfaces define, build a corresponding 
                // method in the dynamic type that calls the handlers invoke method.  
                foreach (Type interfaceType in interfaces)
                {
                    GenerateMethod(interfaceType, handlerField, typeBuilder);
                }

                retVal = typeBuilder.CreateType();

                // assemblyBuilder.Save(dynamicTypeName + ".dll");
            }

            return retVal;
        }
 public static Object NewInstance(AppDomain domain, Type[] interfaces, IProxyInvocationHandler handler)
 {
     return GetProxy(domain, interfaces)
         .GetConstructor(Types_InvocationHandler)
         .Invoke(new Object[] { handler });
 }