Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Be notified of method calls in .NET

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.

like image 730
Alex Avatar asked Jun 03 '10 10:06

Alex


2 Answers

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

like image 90
Mitch Wheat Avatar answered Nov 05 '22 01:11

Mitch Wheat


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

like image 2
Giorgi Avatar answered Nov 05 '22 03:11

Giorgi