How do I intercept a method call in C#?

C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.

I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.

As I understand it, this is what you want to do:

[Log()]
public void Method1(String name, Int32 value);

and in order to do that you have two main options

  1. Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. This article has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I’m talking about a 10x performance lost so think carefully before trying that.

  2. The other option is to inject code directly. In runtime, meaning you’ll have to use reflection to “read” every class, get its attributes and inject the appropiate call (and for that matter I think you couldn’t use the Reflection.Emit method as I think Reflection.Emit wouldn’t allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it’s done.

The final option is using an IoC framework. Maybe it’s not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.

Leave a Comment