Use the Add Reference dialog to make PostSharp a reference in your
project.
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; } } }
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
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); }
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."); } }
You’ve written your first aspect!
Get a daily dose of PostSharp learning with Dustin Davis' new series.
Week 1, Day 1 – OnExceptionAspect
Week 1, Day 2 – Applying Aspects with Multicasting - Part 1
Week 1, Day 3 – Applying Aspects with Multicasting - Part 2
Week 1, Day 4 – OnMethodBoundaryAspect
Week 1, Day 5 – Visual Studio Add-In
Free 30-Day Subscription – Online Training: Aspect Oriented Programming in .NET
Week 2, Day 1 – Your code after PostSharp
Week 2, Day 2 – Interception Aspects – Part 1
Week 2, Day 3 – Interception Aspects – Part 2
Week 2, Day 4 – Aspect Lifetime & Scope - Part 1
Week 2, Day 5 – Aspect Lifetime & Scope - Part 2
Week 3, Day 1 – EventInterceptionAspect
Week 3, Day 2 – Aspect Providers - Part 1
Week 3, Day 3 – Aspect Providers - Part 2
Week 3, Day 4 – Introducing Members and Interfaces
Week 3, Day 5 – Importing Members
1 – Lazy Loading of Dependencies
2 – Caching
4 – Authorization
Learn about the major concepts behind PostSharp, including Aspect-Oriented Programming (AOP) and the PostSharp run-time execution model.