A simple Dynamic Proxy

Posted by Abhijeet Patel on Geeks with Blogs See other posts from Geeks with Blogs or by Abhijeet Patel
Published on Sun, 04 Apr 2010 13:41:33 GMT Indexed on 2010/04/04 22:53 UTC
Read the original article Hit count: 573

Filed under:

Frameworks such as EF4 and MOQ do what most developers consider "dark magic". For instance in EF4, when you use a POCO for an entity you can opt-in to get behaviors such as "lazy-loading" and "change tracking" at runtime merely by ensuring that your type has the following characteristics:

  • The class must be public and not sealed.
  • The class must have a public or protected parameter-less constructor.
  • The class must have public or protected properties
Adhere to this and your type is magically endowed with these behaviors without any additional programming on your part.
Behind the scenes the framework subclasses your type at runtime and creates a "dynamic proxy" which has these additional behaviors and when you navigate properties of your POCO, the framework replaces the POCO type with derived type instances.

The MOQ framework does simlar magic. Let's say you have a simple interface:

 
  1. public interface IFoo  
  2.    {  
  3.        int GetNum();  
  4.    }  

We can verify that the GetNum() was invoked on a mock like so:
 
  1. var mock = new Mock<IFoo>(MockBehavior.Default);  
  2. mock.Setup(f => f.GetNum());  
  3. var num = mock.Object.GetNum();  
  4. mock.Verify(f => f.GetNum());  

Beind the scenes the MOQ framework is generating a dynamic proxy by implementing IFoo at runtime. the call to moq.Object returns the dynamic proxy on which we then call "GetNum" and then verify that this method was invoked.

No dark magic at all, just clever programming is what's going on here, just not visible and hence appears magical!

Let's create a simple dynamic proxy generator which accepts an interface type and dynamically creates a proxy implementing the interface type specified at runtime.

 

 
  1. public static class DynamicProxyGenerator  
  2. {  
  3.     public static T GetInstanceFor<T>()  
  4.     {  
  5.         Type typeOfT = typeof(T);  
  6.         var methodInfos = typeOfT.GetMethods();  
  7.         AssemblyName assName = new AssemblyName("testAssembly");  
  8.         var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);  
  9.         var moduleBuilder = assBuilder.DefineDynamicModule("testModule""test.dll");  
  10.         var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);  
  11.   
  12.         typeBuilder.AddInterfaceImplementation(typeOfT);  
  13.         var ctorBuilder = typeBuilder.DefineConstructor(  
  14.                   MethodAttributes.Public,  
  15.                   CallingConventions.Standard,  
  16.                   new Type[] { });  
  17.         var ilGenerator = ctorBuilder.GetILGenerator();  
  18.         ilGenerator.EmitWriteLine("Creating Proxy instance");  
  19.         ilGenerator.Emit(OpCodes.Ret);  
  20.         foreach (var methodInfo in methodInfos)  
  21.         {  
  22.             var methodBuilder = typeBuilder.DefineMethod(  
  23.                 methodInfo.Name,  
  24.                 MethodAttributes.Public | MethodAttributes.Virtual,  
  25.                 methodInfo.ReturnType,  
  26.                 methodInfo.GetParameters().Select(p => p.GetType()).ToArray()  
  27.                 );  
  28.             var methodILGen = methodBuilder.GetILGenerator();  
  29.             methodILGen.EmitWriteLine("I'm a proxy");  
  30.             if (methodInfo.ReturnType == typeof(void))  
  31.             {  
  32.                 methodILGen.Emit(OpCodes.Ret);  
  33.             }  
  34.             else  
  35.             {  
  36.                 if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)  
  37.                 {  
  38.                     MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)});                          
  39.                     LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);  
  40.                     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);  
  41.                     methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle"));  ));  
  42.                     methodILGen.Emit(OpCodes.Callvirt, getMethod);  
  43.                     methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);  
  44.                                           
  45.                 } 
  46.                else  
  47.                 {  
  48.                     methodILGen.Emit(OpCodes.Ldnull);  
  49.                 }  
  50.                 methodILGen.Emit(OpCodes.Ret);  
  51.             }  
  52.             typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);  
  53.         }  
  54.          
  55.         Type constructedType = typeBuilder.CreateType();  
  56.         var instance = Activator.CreateInstance(constructedType);  
  57.         return (T)instance;  
  58.     }  
  59. }  

Dynamic proxies are created by calling into the following main types: AssemblyBuilder, TypeBuilder, Modulebuilder and ILGenerator. These types enable dynamically creating an assembly and emitting .NET modules and types in that assembly, all using IL instructions.
Let's break down the code above a bit and examine it piece by piece

 

 
  1.            Type typeOfT = typeof(T);  
  2.            var methodInfos = typeOfT.GetMethods();  
  3.            AssemblyName assName = new AssemblyName("testAssembly");  
  4.            var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);  
  5.            var moduleBuilder = assBuilder.DefineDynamicModule("testModule""test.dll");  
  6.            var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);  

We are instructing the runtime to create an assembly caled "test.dll"and in this assembly we then emit a new module called "testModule". We then emit a new type definition of name "typeName"Proxy into this new module. This is the definition for the "dynamic proxy" for type T

 

 
  1.             typeBuilder.AddInterfaceImplementation(typeOfT);  
  2.             var ctorBuilder = typeBuilder.DefineConstructor(  
  3.                       MethodAttributes.Public,  
  4.                       CallingConventions.Standard,  
  5.                       new Type[] { });  
  6.             var ilGenerator = ctorBuilder.GetILGenerator();  
  7.             ilGenerator.EmitWriteLine("Creating Proxy instance");  
  8.             ilGenerator.Emit(OpCodes.Ret);  

The newly created type implements type T and defines a default parameterless constructor in which we emit a call to Console.WriteLine. This call is not necessary but we do this so that we can see first hand that when the proxy is constructed, when our default constructor is invoked.

 

  1. var methodBuilder = typeBuilder.DefineMethod(  
  2.                    methodInfo.Name,  
  3.                    MethodAttributes.Public | MethodAttributes.Virtual,  
  4.                    methodInfo.ReturnType,  
  5.                    methodInfo.GetParameters().Select(p => p.GetType()).ToArray()  
  6.                    );  

We then iterate over each method declared on type T and add a method definition of the same name into our "dynamic proxy" definition

 

 
  1. if (methodInfo.ReturnType == typeof(void))  
  2. {  
  3.     methodILGen.Emit(OpCodes.Ret);  
  4. }  

If the return type specified in the method declaration of T is void we simply return.

 

 
  1. if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)  
  2. {                          
  3.     MethodInfo getMethod = typeof(Activator).GetMethod("CreateInstance",  
  4.                                                       new Type[]{typeof(Type)});                          
  5.     LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                                                
  6.     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);  
  7.     methodILGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));  
  8.     methodILGen.Emit(OpCodes.Callvirt, getMethod);  
  9.     methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);  
  10. }  

If the return type in the method declaration of T is either a value type or an enum, then we need to create an instance of the value type and return that instance the caller. In order to accomplish that we need to do the following:
1) Get a handle to the Activator.CreateInstance method
2) Declare a local variable which represents the Type of the return type(i.e the type object of the return type) specified on the method declaration of T(obtained from the MethodInfo) and push this Type object onto the evaluation stack.
In reality a RuntimeTypeHandle is what is pushed onto the stack.
3) Invoke the "GetTypeFromHandle" method(a static method in the Type class) passing in the RuntimeTypeHandle pushed onto the stack previously as an argument, the result of this invocation is a Type object (representing the method's return type) which is pushed onto the top of the evaluation stack.
4) Invoke Activator.CreateInstance passing in the Type object from step 3, the result of this invocation is an instance of the value type boxed as a reference type and pushed onto the top of the evaluation stack.
5) Unbox the result and place it into the local variable of the return type defined in step 2

 

  1. methodILGen.Emit(OpCodes.Ldnull);  

If the return type is a reference type then we just load a null onto the evaluation stack

 

  1. methodILGen.Emit(OpCodes.Ret);  

Emit a a return statement to return whatever is on top of the evaluation stack(null or an instance of a value type) back to the caller

 

 
  1. Type constructedType = typeBuilder.CreateType();  
  2. var instance = Activator.CreateInstance(constructedType);  
  3. return (T)instance;  

Now that we have a definition of the "dynamic proxy" implementing all the methods declared on T, we can now create an instance of the proxy type and return that out typed as T.

The caller can now invoke the generator and request a dynamic proxy for any type T.
In our example when the client invokes GetNum() we get back "0". Lets add a new method on the interface called DayOfWeek GetDay()

 
  1. public interface IFoo  
  2.    {  
  3.        int GetNum();  
  4.        DayOfWeek GetDay();  
  5.    }  

When GetDay() is invoked, the "dynamic proxy" returns "Sunday" since that is the default value for the DayOfWeek enum

This is a very trivial example of dynammic proxies, frameworks like MOQ have a way more sophisticated implementation of this paradigm where in you can instruct the framework to create proxies which return specified values for a method implementation.

© Geeks with Blogs or respective owner