Scenario

In this sample, you will learn how to develop and use an aspect in 5 minutes.

We suppose here that you have a large, complex project using multithreading. In testing environment, you discover a problem. Unfortunately, you cannot reproduce it on your development machine, where you have the debugger installed. So you decide to trace all calls to the System.Threading namespace.

1. Set up the C#/VB project

In order to use PostSharp Laos, you should add PostSharp.Public.dll and PostSharp.Laos.dll to the list of references of your project. This will import the base classes of all aspects and will insert PostSharp in the build process.

2. Develop the aspect implementation

The following code implements a custom attribute that, when applied on a method, intercepts all calls to this method and prints a message.

using System;
using PostSharp.Laos;

namespace PostSharp.Laos.Test
{
[Serializable]
public class MyOnMethodInvocationAspect : OnMethodInvocationAspect
{
public override void OnInvocation(MethodInvocationEventArgs context)
{
Console.WriteLine("Calling {0}", context.Delegate.Method); context.Proceed();
}
}
}

3. Apply the aspect on target methods

The following piece of code applies this aspect to all methods of the System.Threading namespace:

[assembly: MyOnMethodInvocationAspect(
AttributeTargetAssemblies = "mscorlib",
AttributeTargetTypes = "System.Threading.*")]

If you post-compile an assembly containing these two pieces of code, all calls to methods of the System.Threading namespace will be traced to the console.

4. Execute and build the code

PostSharp will detect all calls to methods of System.Threading and replace them by calls of MyOnMethodInvocationAspect.Invoke.

When you will execute the code, you will see the tracing messages in the console.