Alex
Alex

Reputation: 3470

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.

Upvotes: 6

Views: 1089

Answers (4)

code4life
code4life

Reputation: 15794

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.

Upvotes: 0

kamahl
kamahl

Reputation: 941

you can use extension methods

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

Upvotes: -1

Giorgi
Giorgi

Reputation: 30873

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

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300529

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

Upvotes: 8

Related Questions