views:

412

answers:

3

I am curious to learn if .NET supports any form of dynamic interception of method calls (or properties invoctions) at runtime. That is, can you intercept a call to an object without static compilation information such as an interface (along the lines of the CORBA DII (link text) or COM's IDispatch).

If not, would the new 'Dynamic Typed Objects' feature in C# 4.0 help in this regard.

+1  A: 

Check out the Policy Injection Application Block in Enterprise Library.

JP Alioto
+9  A: 

There is nothing built-in that allows you to intercept an object that you can not control instantiation of. Similarly, there will be no new facilities for this in the upcoming .net 4.0.

If you can control instantiation:

  1. If your object can be MarshalByRef you can use RealProxy.
  2. You could use quite a few IOC containers, eg. LinFu, Castle Dynamic Proxy
  3. You could use a tool like PostSharp, Mono Cecil or Microsoft CCI to rewrite your assemblies with the interceptions as a post compile step.

If you can not control instantiation

  1. You can use ICorDebug - the .Net debugging APIs which are really hard to use and heavy.
  2. You can use ICorProfiler - the .Net profiling APIs where are also pretty complicated to use.

Alternatively, you could look at a dynamic language like IronRuby, which has a built-in alias_method and define_method goodness (which allows you to redefine anything), so interception baked in.

Sam Saffron
You can use RealProxy if you're going through an interface, as well.
kyoryu
I think 'Castle Dynamic Proxy' seems to best fit what I'm looking for. It's API is nice and simple.
karmasponge
Good stuff. One thing to add - Mono.Cecil has some overlaps with PostSharp.
Ruben Bartelink
Thanks Ruben, expanded.
Sam Saffron
A: 

Check out .net 4.0 dynamic objects... That can do it.

http://www.ontheblog.net/CMS/Home/tabid/36/EntryID/77/Default.aspx