Geeks With Blogs

News

Currently Reading

CLR via C#m
Under The Influence(of code) Abhijeet Patel's blog

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.             if (methodInfo.ReturnType == typeof(void))  
  30.             {  
  31.                 methodILGen.Emit(OpCodes.Ret);  
  32.             }  
  33.             else  
  34.             {  
  35.                 if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)  
  36.                 {  
  37.                     MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)});                          
  38.                     LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);  
  39.                     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);  
  40.                     methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle"));  ));  
  41.                     methodILGen.Emit(OpCodes.Callvirt, getMethod);  
  42.                     methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);  
  43.                                           
  44.                 }  
  45.                  else  
  46.                 {  
  47.                     methodILGen.Emit(OpCodes.Ldnull);  
  48.                 }  
  49.                 methodILGen.Emit(OpCodes.Ret);  
  50.             }  
  51.             typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);  
  52.         }  
  53.          
  54.         Type constructedType = typeBuilder.CreateType();  
  55.         var instance = Activator.CreateInstance(constructedType);  
  56.         return (T)instance;  
  57.     }  
  58. }  

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

A client would consume this as follows:

 
  1. static void Main(string[] args)  
  2. {                
  3.     var instance = DynamicProxyGenerator.GetInstanceFor<IFoo>();  
  4.     int num = instance.GetNum();  
  5.     var day = instance.GetDay();
  6.      Console.WriteLine(num);
  7.     Console.WriteLine(day);  
  8.  }  

This is a very trivial example of dynamic 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 as part of Setup.

Posted on Sunday, April 4, 2010 3:41 PM C# | Back to top


Comments on this post: A simple Dynamic Proxy

# re: A simple Dynamic Proxy
Requesting Gravatar...
Very Good Article.
Left by Saravanan on Apr 06, 2010 10:31 PM

# re: A simple Dynamic Proxy
Requesting Gravatar...
Really good article.... helps lot for core understanding of the black magic.
Left by Chirag on Jun 03, 2010 2:36 PM

# re: A simple Dynamic Proxy
Requesting Gravatar...
Nice article, thanks. Seems like a painful way to write IL.. How would you compare this to dynamic code compilation? (See http://bit.ly/JNQWV1 for an example)
Left by Robert on May 02, 2012 10:07 AM

Your comment:
 (will show your gravatar)


Copyright © Abhijeet Patel | Powered by: GeeksWithBlogs.net