tags:

views:

138

answers:

2

I would like to be able to create a runtime proxy for a POCO, in the same style as I might in Java using the JRE or cglib proxying libraries.

I've seen Castle DynamicProxy which looks like it fits the bill, but the documentation isn't great. I'm also surprised that this kind of thing isn't in the .Net Framework itself.

Does anyone:

  • Know of any good resources for Castle DynamicProxy?
  • Know of any alternative approaches?

Thanks!

+1  A: 

This may not be worth much as answers go, but one of the reasons that you don't see a proliferation of dynamic proxies in .NET is that most common .NET languages (C#, VB.NET) differ from Java in one very important aspect:

In Java, all methods are virtual unless explicitly declared sealed.

In C# (and VB.NET IIRC) all methods and properties are sealed unless explicitly declared virtual.

This means that the potential value of a dynamic proxy is far lower in .NET than it is in Java. You have to explicitly design your .NET objects to be 'proxyable', and most people don't do that - it takes a conscious decision to make a .NET object 'proxyable'.

It's actually so rare to see a .NET dynamic proxy outside of DI Containers that I can't think of any other dynamic proxies than Castle.

Note that the 'sealed by default' behavior is a feature of the .NET languages - it is very conceivable that one could design a .NET-based language that has the same 'virtual by default' behavior as Java. Although I don't know any, I would be surprised if such a language does not exist. After all, it's all in the compiler.

Mark Seemann
A: 

"I'm also surprised that this kind of thing isn't in the .Net Framework itself."

There is. Although not complete, elegant or performant. You can use create a generic proxy that inherits from RealProxy and perhaps takes in the object to be proxied. To get the proxy, you obtain a transparentproxy from your realproxy and cast it you your wrapee's (is that a word?) type. Now you have a proxy. All methods on the proxy can be handled in an overridden Invoke(IMessage msg) in your RealProxy. Pass them as is to your real object (wrapee) or do whatever else inbetween.

Cavets: Your object to be proxied has to inherit from MarshalByRef. It is fairly slow. I wouldn't use it for often used functionality. This is all the remoting infrastructure at play here. ILgen is the better way in most cases, but there are some cases where I have had to use above said method.