Summary of presentation "AOP & Policy Injection" that was part of Dot.Net group meeting.

 

Motivation:

  1. Mixing of business logic with supported mechanisms like logging, transaction, security
  2. Code duplication
  3. Same implementation patterns without reuse
  4. Hard maintenance
  5. Lack of modularity 

 

Aspect-oriented programming (AOP) concept:

Separate business logic (functional requirements) from supporting mechanisms (non-functional requirements)  like security, exception handling, tracing, monitoring, transactions, caching, validation.

The way is to encapsulate  supporting mechanisms into Aspects or Policies  and to address them declaratively to business logic code.

 

AOP implementation:

  1. Post-build assembly modification - PostSharp
  2. Metaprogramming - Nemerle
  3. Proxies - Spring.Net, Castle, Policy Injection Application Block

 

PostSharp 

Is framework for AOP implementation on .Net platform  that is started as open-source project. Currently there are versions under open-source and commercial licenses.

Advantages -  easy to start, very “clean” and intuitive code, no config files, debuggable

 

Sample with PostSharp:

 

Define aspect that measures the execution time

 

    public class StopWatchAttribute : OnMethodInvocationAspect

    {

        public override void OnInvocation(MethodInvocationEventArgs eventArgs)

        {

            Stopwatch stopwatch = Stopwatch.StartNew();

            try

            {

 

                eventArgs.ReturnValue = eventArgs.Method.Invoke(

                    eventArgs.Instance,

                    eventArgs.GetArgumentArray());

            }

            finally

            {

                stopwatch.Stop();

                Console.WriteLine("Measure of {0}.{1}: {2} msec",

                    eventArgs.Method.ReflectedType.Name,

                    eventArgs.Method.Name,

                    stopwatch.ElapsedMilliseconds);

            }

        }

    }

 

Address the aspect to function

 

  [StopWatchAttribute]

  public static long CalculateFibonacci(long num)

  {

       Func<long, long> fib = null;

       fib = (x) => x > 1 ? fib(x - 1) + fib(x - 2) : x;

       return  fib(num);

   }

 

Summary:

AOP helps to increase modularity, reduce component coupling, reduce development and maintenance cost.

 

Link to presentation&code  -

http://docs.google.com/a/tikalk.com/leaf?id=0ByN52fnEk8MJOWNkOTZlOGItMzQ...

 

 

2

Comments