Click here to Skip to main content
Click here to Skip to main content

Using AOP in C#

, 9 Jan 2006
Rate this:
Please Sign up or sign in to vote.
Shows how to use AOP with C# and the NKalore compiler. This article also has basic exemples of AOP with NKalore, and shows how to use the AFTER, BEFORE, and AROUND advices.

Introduction

Today, AOP is starting to get attention in the .NET community, and right now, there are a lot of frameworks and compilers for .NET to allow programmers to create .NET applications using AOP.

In this article, I will be talking about the NKalore Compiler. NKalore is a compiler based on MCS (Mono C# Compiler), which allows the use of AOP in your C# code with a very simple and intuitive syntax. So, when developing with NKalore, you will use keywords as ASPECT, POINTCUT, AFTER, BEFORE, AROUND, etc.

Getting NKalore

To start using NKalore, I recommend downloading the latest version at SourceForge. The product is still in an Alpha state, but we already can start to play with NKalore and use AOP in C#.

To compile our samples, we will run NKalore in the command-line mode. At the moment, integration with Visual Studio is not available. It is possible to have a basic integration with #Develop, but it’s a subject for another article.

Creating your first AOP application

In this first sample, I will demonstrate the use of the BEFORE advice, so we can imagine that each time before a specified method is called out, the BEFORE advice will be called.

For this, we create a class that has a method called Sum, as you see below:

using System;

namespace Namespace
{
   public class MainClass
   {
      public void Sum(int a, int b)
      {
         Console.WriteLine("Sum = {0}", a + b);
      }
      
      public static void Main()
      {
         new MainClass().Sum(2,3);
      }
   }
}

Now, we are going to create an aspect so every time the "Sum" method is called, it writes a message into the console. Check it out:

using System;

namespace Namespace
{
   public aspect MyAspect
   {
      pointcut SumPointCut void MainClass.Sum(int a, int b);
      
      before SumPointCut(int a, int b)
      {
         Console.WriteLine(
            "The sum of numbers {0} and {1} will be calculated.", a, b);
      }
   }
}

At first, the pointcut is created to identify which methods to "capture". We have put the full name (class name and method name), but we can also use the ‘%’ character to specify the pointcut like a mask.

Then, the BEFORE advice is created. This advice runs every time the Sum method is called. To compile the application, run NKalore in the command window passing the .cs file as a parameter, for example:

mcs before.cs

Here, mcs in the binary name of NKalore.

When you run the application, you will see the following in the console window:

Logging everything in your code with BEFORE and AFTER advices

The BEFORE and AFTER advices bring with them some information about the method that is being "captured", all this information is inside the "thisJoinPoint" variable. Now, we are going to use these advices to log every code that is executed in our code.

First, we need a class that has a flow built with methods calling a method, just to demonstrate the use of the log:

namespace Namespace
{
   public class MainCls
   {   
      public MainCls() { a(2); }

      void a(int a) { b("paul", 14); }

      void b(string name, double age) { c(true); }

      void c(bool someFlag) { return; }

      public static void Main()
      {
         new MainCls();
      }
   }
}

And now, the aspect that captures all methods, with any name, returning type, or parameter, and logs every thing into the console with information that is in the "thisJointPoint" variable. See the aspect implemented below:

using System;
using System.Reflection;

namespace Namespace
{
   public aspect LoggingAspect
   {
      pointcut LogPointcut % %(...);

      int level = 0;

      void log(NKalore.Model.JoinPoint joinPoint, 
                  string prefix, bool showParams)
      {
         string pad = new string('·', level - 1);
         Console.WriteLine(pad + prefix + " - " + 
                           joinPoint.MethodInfo);                  
         if (showParams)
         {
            ParameterInfo[] pis = 
                  joinPoint.MethodInfo.GetParameters();
            for (int i = 0; i < pis.Length; i++)
            {
               Console.WriteLine(pad + "\t{0} {1} = {2}", 
                  pis[i].ParameterType, pis[i].Name, 
                           joinPoint.ParamsData[i]);
            }
         }
      }

      after LogPointcut()
      {
         log(thisJoinPoint, "after", false);
         level--;
      }

      before LogPointcut()
      {
         level++;
         log(thisJoinPoint, "before", true);   
      }
   }
}

In the aspect, the AFTER and BEFORE advices increment or decrement the "level" variable to keep the level of the stack. And call the "log" method to show in the console, information about thisJointPoint. The output of the application is the following:

The AROUND advice

Another very interesting advice is the AROUND advice. This advice is executed during the execution of the method. So, in reality, when you use this advice, when the method "captured" by the pointcut is executed, your aspect code is executed, and to execute the real method implementation, you need to use the proceed keyword.

To illustrate, we are going to create an aspect with the AROUND advice that calls the implementation of a method (using the proceed keyword). The use of "proceed" is inside a try/catch block, to protect the execution from errors. Take a look at our sample implementation:

using System;
using System.Reflection;

namespace AroundSample
{
   public aspect AroundAspect
   {
      pointcut DoMethods void %.Do%(...);
      
      around void DoMethods()
      {
         try
         {
            Console.WriteLine("Before: {0}", thisJoinPoint.MethodInfo);
            proceed(...);
            Console.WriteLine("After: {0}", thisJoinPoint.MethodInfo);
         }
         catch (Exception ex)
         {
            Console.WriteLine("Error in {0}: {1} ", 
                          thisJoinPoint.MethodInfo, 
                          ex.InnerException.Message);
         }
      }
   }

   public class MainCls
   {
      public void DoSum(int a, int b)
      {
         Console.WriteLine(a + " + " + b + " = " + (a + b));
      }
      
      public void DoMinus(int a)
      {
         Console.WriteLine(a + " - 1  = " + ( a - 1 ));
      }

      public void DoDiv(int a, int b)
      {
         Console.WriteLine(a + " / " + b + " = " + (a / b));
      }

      public static void Main()
      {
         MainCls mainCs = new MainCls();
         mainCs.DoSum(7,3);
         mainCs.DoMinus(5);
         mainCs.DoDiv(5,0);
      }
   }
}

Every method that starts with "Do" is handled by the AROUND advice. First, we log into the console the method that is being executed, writing "before..." and "after...", when the call to the original method is done using proceed keyword. This is made inside a try/catch, block, so if any errors occur (a division by zero will occur in our samples), it will write in the console. The output of this program is:

Another possible use of AROUND, is to cache the results of the function into a hash table, and avoid running the same method twice.

* Note that if you only whish to handle the exception, you can use the THROWING advice.

Conclusion

NKalore offers a very simple way to implement AOP into C#, and it’s very intuitive. The project is still in the Alpha stage, but for a while, we can make little programs with it. As roadmap of NKalore says, in the future, probably we will have some more AOP features and integration with Visual Studio, which would be very nice.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Guilherme Labigalini
Web Developer
Brazil Brazil
No Biography provided

Comments and Discussions

 
GeneralI know this is old article, but... PinmemberPaulo Zemek13-Nov-09 10:49 
GeneralAnother AOP example please Pinmemberjuggler19-Sep-08 2:08 
GeneralRe: Another AOP example please Pinmember3iD0LoN31-May-13 12:31 
GeneralThanks but how does that compare to ... Pinmembertech8127-Oct-06 7:07 
QuestionPerformance? PinmemberJudah Himango14-Sep-06 5:47 
Questionso ? Pinmembertoxcct9-Jan-06 5:44 
AnswerRe: so ? Pinmemberggeurts18-Jan-06 2:13 
GeneralThanks for pointing this out. PinprotectorMarc Clifton9-Jan-06 5:35 
GeneralRe: Thanks for pointing this out. PinmemberJerry Holmes18-Jan-06 11:23 
GeneralRe: Thanks for pointing this out. PinprotectorMarc Clifton18-Jan-06 12:31 
GeneralRe: Thanks for pointing this out. PinmemberJerry Holmes19-Jan-06 4:56 
GeneralRe: Thanks for pointing this out. PinmemberRoger J10-Feb-06 5:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 9 Jan 2006
Article Copyright 2006 by Guilherme Labigalini
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid