• AOP with PostSharp

    Published by jcisneros on June 22nd, 2008 1:49 am under .NET, Uncategorized

    No Comments

    PostSharp is a great open-source tool that allows you to encapsulate the non-business logic in custom attributes. That’s the Aspect Oriented Programming paradigm main goal: the separation of concerns.

    This tool heps you to free the business logic from the infrastructure code such as:

    • Transactions
    • Logging
    • Permissions / Security
    • Exceptions handling
    • Caching
    • Settings

    Your code will be cleaner than never.

    …and why do I call it a “great tool”? Because, unlike other tools that uses reflection and other techniques that reduces performance, PostSharp works at MSIL level!. It generates MSIL code to be injected in your code at compilation time, in that way it supports any .NET language and get the best performance possible.

    Furthermore, this tool is really easy to learn. You can quickly get started by using the basic features, follow this simple quick start:

    The following example shows a simple PostSharp aspect to trace the execution of the methods marked with that attribute:

    public class SimplestTraceAttribute : OnMethodBoundaryAspect
    {
    public
    override void OnEntry( MethodExecutionEventArgs eventArgs)
    {
    Trace
    .TraceInformation(“Entering {0}.”, eventArgs.Method);
    Trace
    .Indent();
    }
    public
    override void OnExit( MethodExecutionEventArgs eventArgs)
    {
    Trace
    .Unindent();
    Trace
    .TraceInformation(“Leaving {0}.”, eventArgs.Method);
    }
    }

    …and it works like a charm!

    The evidence:

    Building the project:

    Inspecting the binaries:

    Results:

    Resources:

    Enjoy it!

    Tags: , ,

  • Leave a comment

    Your email address will not be published.