Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic interception of calls in .NET [closed]

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.

like image 202
karmasponge Avatar asked Aug 26 '09 01:08

karmasponge


1 Answers

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).

like image 141
Sam Saffron Avatar answered Oct 30 '22 21:10

Sam Saffron