How to program using PostSharp in C#

Take advantage of this popular AOP framework to seamlessly manage common functionalities like exception handling, logging, security, and transactions in your application

How to program using PostSharp in C#

Aspect Oriented Programming (AOP) is a programming paradigm that enables you to define policies to seamlessly manage the cross-cutting concerns in applications. AOP can be leveraged to remove intermingled code, write cleaner code, increase code abstraction and modularity, reduce maintenance and development costs, and make applications more manageable and flexible. PostSharp is one of the most popular tools available that can be used to implement AOP in applications.

Getting started

To start using PostSharp, you may want to install the latest stable release using the Package Manager Console. Alternatively, you can install PostSharp using the "Manage NuGet Packages" window. To get started using PostSharp in your application, follow these steps.

1.       Open Visual Studio 2015.

2.       In the Visual Studio menu, click on File > New > Project.

3.       Select the Console Application template from the list of the project templates displayed.

4.       Save the new console application project with a name.

5.       In the Visual Studio menu, click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

6.       Search for the most recent stable release of PostSharp and click Install.

And that's all you need to do for now. When prompted, select the project(s) you want PostSharp to be installed in and click OK. Once the installation is complete, you are ready to use PostSharp in your application.

Programming PostSharp

Once PostSharp is installed, you can get started using it in your application. To do this, you'll need to create one or more aspects for your application to use. One way to implement AOP in your applications is through the use of attributes. Once your aspect has been defined, you'll want to apply the aspect to your program through attributes.

In the Solution Explorer Window, select your project, right click, and add a new class named ExceptionAspect. Note that the aspect needed to handle exceptions in your application should derive from the OnExceptionAspect class of the PostSharp library. OnExceptionAspect includes a method called OnException that you'll need to override to handle exceptions.The following code illustrates our custom exception aspect class.


    public class ExceptionAspect : OnExceptionAspect


        public override void OnException(MethodExecutionArgs args)


            Console.WriteLine("Error occured at: "+

            DateTime.Now.ToShortTimeString() + " Error Message: "+


            args.FlowBehavior = FlowBehavior.Continue;




Every aspect should be serializable -- note the usage of the [Serializable] attribute in the ExceptionAspect class shown above. Now that the aspect is in place, you can apply it on one or more methods in your application using attributes. The following code snippet illustrates a sample method for applying the exception aspect just created.


 public static void TestExceptionAspect()


      throw new Exception("This is a test message");


You can apply the custom exception aspect just created to one or more methods in the application -- or even at the class level. If the aspect is applied at the class level, exceptions thrown by any of the methods of the class would be handled. PostSharp aspects can also be applied throughout the entire assembly. This feature is known as Multicast, and it can be applied to the target namespace by specifying the following statement in the AssemblyInfo.cs file:

[assembly: ExceptionAspect(AttributeTargetTypes = "IDGPostSharp.*")]

"IDGPostSharp.*" in the above code snippet refers to all the types that are present inside the IDGPostSharp namespace.

The OnMethodBoundaryAspect class enables you to execute custom code before and after execution of a method. While its OnEntry method is executed prior to execution of a method on which the aspect is applied, the OnExit method is executed after execution of your method.  The following code listing illustrates how you can measure the execution time of a method using an aspect. The ExecutionTimeAspect class below derives the OnMethodBoundaryAspect class and overrides the OnEntry and OnExit methods.


    public class ExecutionTimeAspect : OnMethodBoundaryAspect



        Stopwatch stopWatch;

        public override void OnEntry(MethodExecutionArgs args)


            stopWatch = Stopwatch.StartNew();



        public override void OnExit(MethodExecutionArgs args)


            string method = new


            string message = string.Format("The method: [{0}] took

            {1}ms to execute.",

                        method, stopWatch.ElapsedMilliseconds);





You can also tweak the OnExit method above to log the execution time of methods. Now that your aspect is ready to be used, it can be applied on one or more methods to retrieve the execution time.


public static void TestExceptionAspect()


   //Some code


You can learn more about PostSharp by reading the documentation.

Copyright © 2016 IDG Communications, Inc.