Getting started with PostSharp

PostSharp makes aspect-oriented programming easy. Follow the guide below, and you can be up and running within minutes.

1. Add a Reference to PostSharp.dll

Use the Add Reference dialog to make PostSharp a reference in your project.


2. Create a custom attribute class as usually

Your aspect will take the form of a .NET attribute that is applied to your code using declarative syntax. Create a new class ending in the suffix Attribute, such as TraceAttribute. That said, you're free to choose another naming convention.

public sealed class TraceAttribute : Attribute { private readonly string category; public TraceAttribute(string category) { this.category = category; } public string Category { get { return category; } } }

3. Derive from OnMethodBoundaryAspect

To make this class an aspect, it must derive from an aspect parent class defined by Postsharp. Import the namespace PostSharp.Aspects, and declare that your aspect will derive from OnMethodBoundaryAspect.

A last thing: the aspect must be made serializable.

using PostSharp.Aspects; [Serializable] public sealed class TraceAttribute : OnMethodBoundaryAspect

4. Implement Advices

Advices are the notifications provided when you enter and exit a method. Add handlers for the OnEntry and OnExit events to capture these notifications. These events are where your aspect will provide its services.

public override void OnEntry(MethodExecutionArgs args) { Trace.WriteLine(string.Format("Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name), this.category); } public override void OnExit(MethodExecutionArgs args) { Trace.WriteLine(string.Format("Leaving {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name), this.category); }

5. Apply Aspects to Methods

A .NET attribute declaration is all it takes to wire your new aspect into one or more existing class methods. Add your aspect to an entire class to add your new behavior to all the class methods, or apply it only to individual methods.
internal static class Program { private static void Main() { Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); SayHello(); SayGoodBye(); } [Trace("MyCategory")] private static void SayHello() { Console.WriteLine("Hello, world."); } [Trace("MyCategory")] private static void SayGoodBye() { Console.WriteLine("Good bye, world."); } }

6. Compile and Execute

You’ve written your first aspect!