Aspect Oriented Programming (AOP) In .Net Using C#



I recently had a chit-chat with some developers and during our discussion, I asked them whether they do Aspect Oriented Programming (AOP), I was surprised with their responses, some of them have not heard of the concept before while others have heard of it but without bothering to investigate it. I further asked them how they manage cross cutting concerns in their codes and they told me their various implementations, in which I drew my conclusion; they have been writing repetitive codes that would definitely stink and be hard to manage.

Aspect oriented programming is a new concept in the software development world; it makes you write clean codes and prevents weaving of functional codes with non-functional codes, thereby reducing code repetition. By non-functional codes I mean cross cutting concerns like logging, caching, auditing and so on.

Imagine the kind of spaghetti codes that trying to log all methods in an enterprise application with a large codebase without the use of AOP to simplify it would produce. The ActionFilters in ASP.net MVC are examples of the implementation of AOP.

To fully grasp AOP, some terminology and concepts need to be understood. ADVICE- This is the code that performs cross cutting concern. A cross cutting concern can be logging or caching. It might be a piece of code that does logging in an application. POINTCUT -A Pointcut is that point in a program where the advice would be called and executed; it can be just before a method gets called or just before a class is instantiated.

There are cool AOP tools available for .net developers, that can make your AOP experience smooth and worthwhile, thus, preventing you from to re-inventing the wheel. The two most popular are PostSharp and CastleWindsor. I prefer the former because it is elegant and allows you to use the advice at the pointcut in a decorative pattern approach, this is not to say that the later is not robust I have equally used it in some projects. The example in this blog post uses PostSharp.

Navigate your browser to www.postsharp.net to download the latest installation. The postsharp package when installed adds itself as a plugin to your installation of visual studio, so that subsequently you can just add the postsharp package to your project by right clicking the project in solution explorer to select Add Postsharp to project.

I will demonstrate this using a console application, create a console application in visual studio and then add postsharp library to the project. Add a new class to the project and name it MyLoggerClass. It is this class that will contain the cross cutting concern. In this case we will write on the console before the method is called and immediately after the method finishes execution. In real life scenario, you might want to log a method for auditing sake to know when and whether the method is called and if the method successfully executed.

Postsharp requires that any class to be used as an aspect class to be serializable, hence the decoration of the class with .Net's Serializable attribute. The MyLoggerClass will extend the Postsharp OnMethodBoundaryAspect, which makes it necessary for the MyLoggerClass to override the OnEntry and OnSuccess methods of OnMethodBoundaryAspect since I am concerned with logging when the method is called and after the method finishes exectution. The OnMethodBoundaryAspect has OnExit and OnException Methods that you can equally override if you are concerned with these events in your application.

The full code for the MyLoggerClass class is as shown below.

using PostSharp.Aspects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace AOP
{
    [Serializable]
    public class MyLoggerClass : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("This code got executed before the method was invoked");
        }

        public override void  OnSuccess(MethodExecutionArgs args)
        {
            Console.WriteLine("This code got executed after the method was invoked");
        }
    }
}
        


In the Program.cs class of the console application, add a new class and name it InterceptedClass. Add a method to it and decorate the method with the attribute MyLoggerClass, as shown below.

    public class InterceptedClass
    {
        [MyLoggerClass]
        public void DoSomething()
        {
            Console.WriteLine("DoSomething method was called");
        }
    }
        


Then in the main method, instantiate the InterceptedClass and call the method you added to the class as shown below.

    private static void Main(string[] args)
    {
        InterceptedClass interceptedClass = new InterceptedClass();
        interceptedClass.DoSomething();
        Console.ReadLine();
    }
        


Run the program, you should see the screen as below.



This is a simple demonstration of AOP, this blog post should get any developer interested in AOP started, Postsharp has other cool features not described in this blog post. You can read further on the Postsharp website .

Click Here to download the complete source code of the console application.




Share this page on


  8 People Like(s) This Page   Permalink  

 Click  To Like This Page

comments powered by Disqus

page