How to do Dynamic Proxies in C

Background: A dynamic proxy dynamically generates a class at runtime that conforms to a particular interface, proxying all invocations to a single ‘generic’ method.

Earlier, Stellsmi asked if it’s possible to do this in .NET (it’s a standard part of Java). Seeing as it’s the second time I’ve talked about it in as many days, I reckon it’s worth blogging…

As far as I know, there are two ways to do this:

The first approach is pretty trivial, but it locks you into the fact that you can only proxy objects that extend ContextBound. Not ideal as this pulls a lot of stuff into your class you don’t necessarily need and prevents you from inheriting something else.

The second approach is more suitable, less intrusive, but not pretty to write as it involves writing low-level IL op-codes. However, I did this already in NMock and at GeekNight, Steve and Jon lovingly decoupled the ClassGenerator from the core of NMock, so you can create generic dynamic proxies. So now it’s easy to create a proxy.

h3. Example

Here’s an interface you want to create a dynamic proxy for:

interface IFoo {
string DoStuff(int n);
}

Note:

To create the proxy, you need to create an implementation of IInvocationHandler. This is called any time a method is invoked on the proxy.

class MyHandler : IInvocationHandler {
public object Invoke(string methodName, param object[] args) {
return "hello from " + methodName;
}
}

Notes:

Finally, you need to generate the proxy itself so you can actually use the damn thing:

ClassGenerator generator = new ClassGenerator(
typeof(Foo), new MyHandler()  );
IFoo fooProxy = (IFoo)generator.Generate();

string result = fooProxy.DoStuff(2); // returns "hello from DoStuff"

Ermm and that’s it! Use your dynamic proxy like it’s a real class.

ClassGenerator is part of the NMock library. Use it for AOP style interceptors, decorators, stubbing, mocking :), whatever.

Brain rumblings… Hmm… maybe that should be a delegate instead… maybe I should revisit some stuff…