views:

201

answers:

3

When using NHibernate, you define your entites with virtual methods, and NHibernate will create a proxy object that tracks changes to your object.

In Moq, the framework will magically create a derived type from an interface or a base class. e.g.

var mock = new Mock<IFoo>();
IFoo magicFoo = mock.Object;

This is really cool. How do these frameworks do it? Do they use reflection, generics, some kind of dynamic compilation, or something else?

I realize these are both open source projects, and I could go spelunking through the code, but I'd like to have a concise answer here - possibly with alternatives.

+1  A: 

Castle's DynamicProxy2 class.

Chris Missal
+1  A: 

They use a combination of reflection (to figure out what needs to be generated) and reflection-emit (to generate the derived class dynamically, and emitting IL for the methods). .NET provides both of these APIs (reflection and reflection-emit).

Justice
If you don't mind using beta stuff, the .NET Framework 4 actually lets you invoke the compiler at runtime so you can generate it from C# code instead of having to resort to ilasm, etc.
Robert Fraser
+2  A: 

Moq uses Castle Dynamic Proxy, however, just thought it would be worth adding there are also a number of other frameworks that allow you to create Proxy objects. As of NHibernate 2.1 it also allows you to use any one of the following:

Each of these projects has a brief explaination of how they achieve this, which is hopefully the kind of answer you're looking for.

Brendan Kowitz