Aspect oriented programming in .NET

Came across an article about implementing AOP in .Net CLR. Very interesting approach imho. Something between AspectJ’s relatively static approach and Rickard’s relatively dynamic and configurable approach. Rickard, what do you think about it?

-Ara Abrahamian

This approach to AOP in .NET seems a bit overkill. After reading what Rickard was doing with AOP whilst stuck on a .NET project, I found it hard to resist creating a little AOP framework. Here’s an example of usage…

Take this class:

[Aspectable]
public class Thing extends ContextBound {
  // Annoying constraint:
  // Classes need to extend ContextBound and have Aspectable attribute.

  public void DoStuff(string name) {
    Console.WriteLine("Hello " + name);
  }

  public static void Main(string[] args) {
    // command line entry point

    Thing t = new Thing();
    t.DoStuff("Joe");
  }
 
}

Which outputs:

Hello Joe

To add an aspect, just place create a class like this, add to assembly and it’ll automagically do its stuff:

[Aspect]
public class MyAspect {

  [Pre, Match("Thing.*")]
  public void FigureOutFullName(CutPoint cut) {
    string name = (string)cut["name"];
    if (name == "Joe") {
      cut["name"] = "Joe Walnes";
    }
  }
 
  [Post, Match("Thing.*")]
  public void SayBye(CutPoint cut) {
    Console.WriteLine("Bye " + cut["name"]);
  }
 
}

Now the original invocation outputs:

Hello Joe Walnes
Bye Joe Walnes

Aspects can be invoked before and after method/constructor/property calls specified with by full-name, wildcard or regexp. The CutPoint class provides a context allowing the parameters, return type or thrown exception to be modified and optionally to cancel the call to the real method. Multiple aspects can be applied to a single call and priorities can be specified. The aspects can be modified at runtime.

The implementation was pretty simple (four small classes) and I unfortunately never got a chance to use it on my project (which has now finished) - but maybe the next one. Strangely aspects are not built into the CLR, but nearly all the features to create them are there - shame MS didn’t standardize on this.