A basic proxy for intercepting method calls (Part –1)

In this post, i am going to show how you can write your own proxy for delegating calls. This just shows a way how you can handle it on your own but for complex interceptions its always wise to use alpha/beta/tested solutions. The post is more of an under the hood or aims to solve simple interception tasks where you might not need a full featured dynamic proxy or can be useful in building something that requires similar techniques which can move you further.

Let’s start by considering a simple class

  1. public class TestClass
  2. {
  3.     public virtual void TestCall()
  4.     {
  5.         throw new Exception("Failed.");
  6.     }
  7. }

Here, during the creation of proxy i will hook the method with an interceptor that will alternate the execution process from original code. At a glace, our interceptor looks like:

  1. public interface IInterceptor
  2. {
  3.     void Intercept();
  4. }

As it shows, we are going to do a fairly basic implementation.To start, let’s create an implementation on it named BasicInterceptor where inside the Intercept call it just prints a line.

  1. public class BasicInterceptor : IInterceptor
  2. {
  3.     public void Intercept()
  4.     {
  5.         System.Console.WriteLine("Intercepted");
  6.     }
  7. }

Once, we are done with our proxy the result code will look something like below:

  1. var proxy = new Proxy(typeof(TestClass));
  2. var test = (TestClass) proxy.Create(new BasicInterceptor());
  3.  
  4. test.TestCall();

And the above test.TestCall() call Instead of throwing an exception, it will print our expected line. We can here see that I first created the proxy with the given type/class then during the instantiation i hooked that up with our interceptor. Hence, on my first step I created a class deriving from the specified type and  expanded its constructor(s) to take an IInterceptor implementation as parameter.

Accordingly, I first created a TypeBuilder instance from System.Refleciton.Emit which is pretty much common in all kind and that looks like:

  1. AssemblyName assemblyName = new AssemblyName("BasicProxy");
  2. AssemblyBuilder createdAssembly =  AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
  3. // define module
  4. this.moduleBuilder = createdAssembly.DefineDynamicModule(assemblyName.Name);

That is followed by:

  1. this.typeBuilder =
  2.     this.moduleBuilder.DefineType(target.FullName, TypeAttributes.Class | TypeAttributes.Public, target);

In the proxy , I defined a field named “interceptor” that will be assigned with the passed-in user-defined implementation.

  1. this.fldInterceptor = this.typeBuilder.DefineField("interceptor", typeof (IInterceptor), FieldAttributes.Private);

Now, for each constructor let’s expand it to have IInterceptor as first argument, call the corresponding base and set it to our defined field.

  1.  Type[] parameters = new Type[1];
  2.  
  3.  ParameterInfo[] parameterInfos = constructor.GetParameters();
  4.  parameters = new Type[parameterInfos.Length + 1];
  5.  
  6.  parameters[0] = typeof(IInterceptor);
  7.  
  8.  
  9.  for (int index = 1; index < parameterInfos.Length; index++)
  10.  {
  11.      parameters[index] = parameterInfos[index].ParameterType;
  12.  }
  13.  
  14.  ConstructorBuilder constructorBuilder =
  15.      typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameters);
  16.  ILGenerator generator = constructorBuilder.GetILGenerator();
  17.  
  18.  
  19.  
  20.  generator.Emit(OpCodes.Ldarg_0);
  21.  
  22.  for (int index = 1; index < parameters.Length; index++)
  23.  {
  24.      generator.Emit(OpCodes.Ldarg, index + 1);
  25.  }
  26.  
  27.  generator.Emit(OpCodes.Call, constructor);
  28.  
  29.  generator.Emit(OpCodes.Ldarg_0);
  30.  generator.Emit(OpCodes.Ldarg_1);
  31.  generator.Emit(OpCodes.Stfld, fldInterceptor);
  32.  generator.Emit(OpCodes.Ret);

 

Tip 1 : OpCodes.Ldarg_0 is like “this” context, which is not needed for static calls. If your are calling a field of the class or referring method arguments, always start with LdArgs_0 or you might end up with “JIT encountered an internal limitation” error.

Tip 2: In MSIL every method must terminate with OpCodes.Ret regardless its void or not. The difference between void and non-void calls is that the top of evaluation stack is not empty.

Now, as we set it up , we need to hook the interceptor in each method that is marked as virtual. First, let’s create the target method attribute :

  1. const MethodAttributes targetMethodAttributes =
  2.     MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;

Next, for each method that is not final hook the IInterceptor.Intercept() call.

  1. if (methodInfo.IsVirtual)
  2. {
  3.     Type[] paramTypes = GetParameterTypes(methodInfo.GetParameters());
  4.  
  5.     MethodBuilder methodBuilder =
  6.         typeBuilder.DefineMethod(methodInfo.Name,targetMethodAttributes, methodInfo.ReturnType, paramTypes);
  7.  
  8.     ILGenerator ilGenerator = methodBuilder.GetILGenerator();
  9.  
  10.     ilGenerator.Emit(OpCodes.Ldarg_0);
  11.     ilGenerator.Emit(OpCodes.Ldfld, fldInterceptor);
  12.     ilGenerator.Emit(OpCodes.Callvirt, typeof(IInterceptor).GetMethod("Intercept"));
  13.  
  14.     ilGenerator.Emit(OpCodes.Ret);
  15. }

 

Again, before loading the interceptor field on to the evaluation stack , I used Ldarg_0 or “this” equivalent . If you notice, you will see that I have used OpCodes.Callvirt instead of OpCodes.Call. This will actually call the base method rather the implemented. This difference is important if you need to distinguish between base and implemented calls. Unless otherwise, it is better to go with OpCodes.Callvirt that will do the work for you if “base” is something not in your consideration.

Finally, you need to create the type and instance that will be initiated by Proxy.Create() call.

  1. Type proxy = this.typeBuilder.CreateType();
  2. return Activator.CreateInstance(proxy, args);

That’s it, we ended up with a simple proxy. In the next post, i will enhance it with parameters consideration and show how to handle return value from proxy.

Happy new year !!

Edit : Removed the download , please check the latest post for one.

No Comments