8

I am curious to learn if .NET supports any form of dynamic interception of method calls (or properties invocations) 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 'Dynamically Typed Objects' feature in C# 4.0 help in this regard.

Kirill Osenkov
  • 8,786
  • 2
  • 33
  • 37
karmasponge
  • 1,169
  • 2
  • 12
  • 26

1 Answers1

19

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.


In .NET 4.5, the aforementioned ICorProfiler is introducing a method to ReJIT methods which provides another hook for method interception (provided you are not running a concurrent/bg GC and the method is not inlined).

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Sam Saffron
  • 128,308
  • 78
  • 326
  • 506