views:

120

answers:

4

I want to be notified whenever a specific method has been called. I was hoping I could accomplish this using Reflection, but my attempts haven't gotten me anywhere. How can I be notified?

I figured using MethodInfo was the way to go, but like I said, I found nothing there that could help me accomplish what I wanted to do.

I cannot change the method or decorate it with attributes or anything. If I could do something like that, I wouldn't need to do this, I could just change the method itself.

+7  A: 

Have you considered AOP (aspect-oriented programming)? Something like PostSharp.

Mitch Wheat
+1 I would definitely use this method!
PieterG
+1 You can also achieve AOP-like features without PostSharp using nothing but Decorators: http://blog.ploeh.dk/2010/04/07/DependencyInjectionIsLooseCoupling.aspx
Mark Seemann
a decorator is also a good idea
Mitch Wheat
+2  A: 

I believe the only way to do this is either rewrite the method body so that it notifies you when the method has been called or use CLR Profiling Api.

The first way can be accomplished by using AOP framework. You can use Postsharp (which was turned into a commercial product) to achieve it with OnMethodBoundaryAspect. Here is an example: Derive the class from OnMethodBoundaryAspect

Giorgi
A: 

you can use extension methods

so you can use different attributes and modify everything before or after the actual method

Patrick Säuerl
I'm not the one calling these methods. I can't make the original code suddenly call my extension methods. So no go.
Alex
A: 

Reflection is half the solution. You need to wrapperize the objects being observed in order to intercept the method calls. Usually thi is done via remoting proxy objects.

Enterprise Library has the Unity Interception block which does exactly what you want. Also you may want to look into Castle framework's DynamicProxy, which gives you extremely thorough control of this interception process.

Googling for Aspect Oriented Programming will give you more information.

code4life