List executed code using PostSharp
There where many good ideas and your truly suggested using PostSharp – mainly because this is one of the examples I use in my AOP and PostSharp presentation. And so without further ado here is my solution for your consideration:
The “tracing” attribute
For this purpose I choose to use OnMethodBoundaryAspect which enable me to add hooks on method’s enter and exit:
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple = true)]
public class TraceMethodCallsAttribute : OnMethodBoundaryAspect
{
private string _methodName;
public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo)
{
_methodName = method.DeclaringType.Name + "." + method.Name;
}
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine(">> {0}", _methodName);
}
public override void OnExit(MethodExecutionArgs args)
{
Console.WriteLine("<< {0}", _methodName);
}
}
This is your simple method boundary aspect which is good to add custom functionality before and after method call as well as on exception and/or successful completion. This time I only needed the enter and exit functionality.
My attribute has several attribute of it’s own, one simple for serialization and the other is where the magic happens – the MulticastAttributeUsage that tells PostSharp that this attribute should be automatically applied to every method in the class or assembly.
Other than that I’ve also used CompileTimeInitialize in order to save some cycles by “calculating” the method name only once (at compile time) instead of each time the method is called.
Using the attribute
Now all I have to do is add this line to the AsseblyInfo.cs file:
[assembly: TraceMethodCalls]
And that’s it – running the following program:
class Program
{
static void Main(string[] args)
{
var a = new A();
for (int i = 0; i < 3; i++)
{
a.MethodOne();
a.MethodTwo();
}
}
}
public class A
{
public void MethodOne()
{
Console.WriteLine("I am in method one");
}
public void MethodTwo()
{
Console.WriteLine("I am in method two");
}
}
Provides the desired result
Happy coding…
References: List executed code using PostSharp from our NCG partner Dror Helper at the Helper Code blog.