A few days ago, I wrote a small Dynamic Proxy class.  It wasn't anything fancy and there are already a few more then adequate libraries that already have this functionally. (Linfu and Castle Project's DynamicProxy).  I was mainly looking for an excuse to futz around with CodeDomProvider and the dynamic proxy seemed like a problem tailor-made for a CodeDom solution..or so I thought.  The dynamic proxy problem is pretty straight forward and my solution was simple enough.  Given:

public class SomeClass : ISomeInterface

{

           public void SomeMethod(string someText)

           {

                          

            }

}

With ISomeInterface defining SomeMethod.  Generate a class that looks like this:

public class SomeClassProxy: ISomeInterface

{

             private ISomeInterface someClass;    

             public SomeClassProxy(ISomeInterface someClass)

             {

                                 this.someClass = someClass;

              }

              public void SomeMethod(string someText)

              {

                               this.someClass.SomeMethod(someText);

              }

}

I also added some events that were raised before and after invocation.  Sort of a poor man's AOP interceptor.  Overall, nothing more then a classic GOF Proxy.  So given a class that implemented some interface, I needed the proxy to be generated at runtime.  Using my simple Dynamic Proxy looks something like this:

ISomeInterface obj = new SomeClass();

Proxy proxy = new Proxy<ISomeInterface>();

ISomeInterface objProxy = proxy.Create(obj);

The Proxy class does all of the things you would expect it to.  It uses Reflection to find the public interface of ISomeInterface. Then it creates the SomeClassProxy shown above at runtime with CodeDomProvider.  Next it instantiates that class, passing in obj to the constructor with Reflection.  Everything works as expected.  However, as you might have guessed, its a bit slow. And that's because CodeDomProvider is creating the C# code and compiling it into MSIL at runtime. And when the SomeMethod on the SomeClassProxy class is actually executed it is then JIT compiled into machine code.

The solution: Use Reflection.Emit to emit the MSIL instead of CodeDomProvider to generate and compile C#.  Effectively getting rid of the middleman and the extra compilation step.

The problem: Reflection.Emit is hard.  It's full of code that looks like this:

ILGenerator ilg = methodBuilder.GetILGenerator();

ilg.Emit(OpCodes.Ldc_I4_0);

ilg.Emit(OpCodes.Ldarg_S, 13);

ilg.Emit(OpCodes.Ret);

Which is pretty cryptic without deep understanding of MSIL.  The reality is that every .NET developer should be at least familiar with IL even if you have no plans to ever use Reflection.Emit.  Its an invaluable tool in understanding performance considerations and debugging bizarre bugs where the high level code looks solid but behaves oddly. 

And so begins my journey...