Creating a basic proxy for intercepting [quick update].

In my previous post, i enhanced the proxy to support generic calls. In order to minimize IL emit and move more parts to managed code, there is a better way to process the return value rather doing the checks against runtime method and see whether the method’s return type is a value or not for generic calls to un-box the object form that is returned from the interceptor.

Therefore,  i replaced the return value processing from my previous with the following

  1. if (methodInfo.ReturnType != typeof(void))
  2. {
  3.     ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
  4.     ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInvocation).GetMethod("get_ReturnValue"));
  6.     if (!methodInfo.ReturnType.IsGenericParameter)
  7.     {
  8.         if (methodInfo.ReturnType.IsPrimitive || methodInfo.ReturnType.IsValueType)
  9.         {
  10.             ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
  11.             ilGenerator.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
  12.         }
  13.         else if (methodInfo.ReturnType.IsValueType)
  14.         {
  15.             ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
  16.         }
  17.     }
  18.     else
  19.     {
  20.         ilGenerator.Emit(OpCodes.Unbox_Any, methodInfo.ReturnType);
  21.     }
  22. }

Here, for generic return there is a different IL instruction to perform the un-boxing and for that we don’t need the runtime type [done in previous post]. The instruction is same as doing

T ret = (T)returnValue; // where returnValue is in object form

To make the basic proxy look more pretty, i added a silverlight project and added the Xunit tests from C# library that asserts the proxy is compatible in silverlight runtime with no pitfalls.

The Xunit tests are ported to silverlight using the Xunit Light wrapper by Jason Jarett that works seamlessly on top Microsoft Sliverlight Unit Testing Framework and just with an F5 gives you a nice output which can easily be registered by adding the following line in your App.xaml.cs.


  1. //*******************
  2. // Register the XUnitTestProvider with the Microsoft.Silverlight.Testing framework.
  3. UnitTestSystem.RegisterUnitTestProvider(new Microsoft.Silverlight.Testing.UnitTesting.Metadata.XunitLight.XUnitTestProvider());
  4. //*******************
  5. this.RootVisual = UnitTestSystem.CreateTestPage();



Finally, its still a simple proxy, plenty of things are missing and i will cover them up overtime but gives a way to get your feet wet with MSIL. You can download the latest proxy here 

The link to the previous post follows   A basic proxy for intercepting method calls (Part – 3).


1 Comment

Comments have been disabled for this content.