Tuesday, December 21, 2010

Aspects and AOP

Aspects and AOP

Aspect Oriented Programming (AOP) is a paradigm that separates supporting functionality from business logic. It is useful for addressing Cross Cutting Concerns.

AOP is generally implemented by defining code that executes before, around, and/or after a point in business code. For example, you could define some code to execute (which is known as advice) every time a method is accessed. This code could log access, check permissions, pretty much anything you want it to do.

In the .NET world, AOP is accomplished via Attribute Programming, using a 3rd party assembly for functionality. The biggest example I found in the community was PostSharp, which I used to implement security checks in sample code. PostSharp will intercept calls to a method, property, class, etc and perform the advice as needed. So a pseudo-example might be:

<SecurityAspect(RoleEnum.Manager)> _
Public Sub GiveRaiseTo(Employee as Employee)

So what's with the SecurityAspect attribute?

Well, it would look something like this:

Public Class SecurityAspect
    Inherits MethodInterceptionAspect

Private _role As RoleEnum

    Public Sub New(Role as RoleEnum)
        _role = Role
    End Sub


 

    Public Overrides Sub OnInvoke(args as MethodInterceptionArgs)
        If Not User.Role.Equals(_role) Then
            Throw New InvalidAccessException("You are not allowed here!")

        Else
            MyBase.Invoke(args)

End If
End Sub

End Class

So what is happening here? Whenever any consuming code calls GiveRaiseTo(), the Aspect is going to execute and test the User Role against the Role that was passed in, and throw an exception if they don't match. That means, in this instance, only Managers can access the GiveRaiseTo() method.

Read more on PostSharp here.

No comments:

Post a Comment