Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in .NET to have a method called automatically after another method has been invoked but before it is entered

Tags:

c#

.net

What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example:

public class Test {

  public void Tracer ( ... )
  {
  }

  public int SomeFunction( string str )
  {
    return 0;
  }

  public void TestFun()
  {
    SomeFunction( "" );
  }

}

In the example above I would like to have Tracer() called after SomeFunction() has been invoked by TestFun() but before SomeFunction() is entered. I'd also like to get reflection data on SomeFunction().


I found something interesting in everyone's answers. The best answer to the question is to use Castle's DynamicProxy; however, this is not that I'm going to use to solve my problem because it requires adding a library to my project. I have only a few methods that I need to "trace" so I've chosen to go with a modified "core" methodology mixed with the way Dynamic Proxy is implemented. I explain this in my answer to my own question below.

Just as a note I'm going to be looking into AOP and the ContextBoundObject class for some other applications.

like image 980
jr. Avatar asked Oct 10 '08 17:10

jr.


2 Answers

You can use a dynamic proxy (Castle's DynamicProxy for example) to intercept the call, run whatever code you wish, and then either invoke your method or not, depending on your needs.

like image 161
Ben Hoffstein Avatar answered Oct 20 '22 11:10

Ben Hoffstein


Use a *Core method:

public int SomeFunction(string str)
{
    Tracer();
    return SomeFunctionCore(str);
}

private int SomeFunctionCore(string str)
{
    return 0;
}

A number of the .NET APIs use this (lots do in WPF).

like image 38
Bob King Avatar answered Oct 20 '22 10:10

Bob King