Dynamic Proxy How To (1)
 
This is the article I promised for a while, how to create your own dynamic proxy. I am only trying to explain the basic idea of it with the simple example we can understand, and if you want a more sophisticated library, use castle www.castleproject.org

There is a good detail explain about the proxy pattern.

The idea is quite simple. To intercept some functions, we create a subclass of the real object you want to intercept, and pass the interceptor interface into the generated subclass (ioc?), so during each call of the method, you can call the interceptor method first or after with added behavior. This all happened in runtime to make it invisible process to users. We have to use reflection emit class to dynamic generate the IL codes to make all these happen

So in the client side, you are using the following line to instantiate your class rather than the new operator. 

MyClass my = (MyClass)ProxyFactory.Create(typeof(MyClass), Interceptor)

Interceptor is the customized cross-cutting class you created based on some interface.

In the proxyfactory class, we are using create to create a new type of class and inherit from MyClass. here is the procedure,
we need to define the type first in the current application domain

            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name 
= "DynamicAssemblyProxyGen";

            AssemblyBuilder ab 
= System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder module 
= ab.DefineDynamicModule(assemblyName.Name);

            TypeBuilder childClass 
= module.DefineType("SimpleClassChild", TypeAttributes.Public|TypeAttributes.Class, typeof(SimpleClass));



 

And create the constructor match the base class

            ConstructorInfo superConstructor = type.GetConstructor(new Type[0]);
            ConstructorBuilder constructor1 
= childClass.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);
            ILGenerator constructorIL1 
= constructor1.GetILGenerator();
            constructorIL1.Emit(OpCodes.Ldarg_0);
            constructorIL1.Emit(OpCodes.Call, superConstructor);
            constructorIL1.Emit(OpCodes.Ret);


 

Mix in the interceptor object as its member field

FieldBuilder interceptField = childClass.DefineField("interceptor1", inter.GetType(), FieldAttributes.Private);


Loop through the overrideable method to call the base method and the interceptor defined method. In some case, we don't really need to override the method. Also, EmitMethod is another function to get the argumentlist of the baseclass and generate a compatible one.

            MethodInfo[] methodInfoList = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            
foreach (MethodInfo method in methodInfoList)
            
{
                
if (method.IsPrivate || !method.IsVirtual || method.IsFinal || method.IsAssembly)
                
{continue; }
                
if (method.DeclaringType.Equals(typeof (Object)) && !method.IsVirtual)
                
{continue;}
                
if (method.DeclaringType.Equals(typeof (Object)) && "Finalize".Equals(method.Name))
                
{continue;}

                MethodInfo simpleMethod 
= EmitMethod(childClass, method, interceptField);
                childClass.DefineMethodOverride(simpleMethod, method);
            }

 
In the end, create the type and its instance using Activitor and return.

            Type t = childClass.CreateType();
            Object[] args 
= new object[1]{inter};
            
return Activator.CreateInstance(t, args);


That is it. The full codes can be downloaded here.
 hope it can explain itself.