Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept method calls

Is there a way of intercepting some method calls without making any code changes around the method itself?

I don't need to inject any custom behaviour at runtime, only add custom performance logging to an existing project.

like image 385
aly Avatar asked Nov 28 '22 16:11

aly


1 Answers

You want Aspect Oriented Programming.

There are 4 main flavours of AOP

  1. Runtime RealProxy based AOP
  2. Runtime subclass/virtual method AOP
  3. Post Compile IL weave AOP
  4. Precompile source code AOP

The above are ordered in order of speed of execution (slowest to fastest). Note the last two "should" be the same speed. However I expect the compiler to produce better IL than a Post Compile IL weave.

The first camp usually includes IOC containers, since they lend themselves fairly well to this pattern, including and not limited to

  • Unity
  • Spring.NET
  • Castle.Windsor
  • Postsharp Express

The second camp, is pretty rare, and the only project that I can think of off the top of my head is Entity Framework (which uses it for Lazy loading, however it isn't extensible, and cannot be customised).

The third camp is pretty sparce also, since this technique is extremely complicated and difficult. This works by editing the dll assembly AFTER you have compiled, to add the extra code you want.

  • Postsharp Pro
  • Mono.Cecil
  • Fody (a mono.cecil wrapper)

The final camp is relatively new. So new in fact, the only real entry is the experimental MS Roslyn. This is actually a C# compiler. So...yeah...its pretty magic.

Now, if you are having real huge performance issues with performance critical code, I would suggest using Fody. What is awesome about this, is that it is free (unlike Postsharp Pro), it uses nuget and there is already a performance tool in Fody.MethodTimer.

like image 59
Aron Avatar answered Dec 14 '22 15:12

Aron