Tomorrow night I’m doing a demo at Philly.Net on AOP. It’s a pretty cool technology that allows you to deal with cross cutting concerns in a pretty easy way. Write your code once (code for exception handling, logging, security, etc.) in an Aspect. Then you can easily reuse that same aspect throughout your application by simply decorating methods with an attribute.

If you attended my demo, you may want the source code… here it is.

If you are just curious, here is some sample code:

A simple Trace Aspect:

using System;
using System.Diagnostics;
using PostSharp.Aspects;

namespace AOPSample
{
    [Serializable]
    public sealed class TraceAttribute : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Trace.WriteLine(string.Format("Entering {0}.{1}",
                args.Method.DeclaringType.Name, args.Method.Name));
        }

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

    }
}

I want to write to the Trace log everytime DoSomething() gets called, so I decorate it with the Trace attribute!:
using System;

namespace AOPSample
{
    public class ServiceThatNeedsTracing
    {
        [Trace]
        public void DoSomething()
        {
            //it doesn't matter what is here.
        }
    }
}
When I run my application and call the DoSomething() method, I’ll get this in the Trace Window:
Entering ServiceThatNeedsTracing.DoSomething
Leaving ServiceThatNeedsTracing.DoSomething
Isn’t that easy?