Monday 28 March 2011

Dot.net: AOP with PostSharp - Property accessor modified

Question:
How can I change a property getter for all my properties by using AOP?
How to use PostSharp, an Aspect Oriented Programming framework, to intercept property getter calls.


Answer:
Here I will show a simple setup that I use with PostSharp. (free community version)

I just want to modify the result string of some of my Properties by annotating them with a custom attribute.

You can always use other popular AOP frameworks (Castle Windsor, Spring.NET, Microsoft Unity etc.) as alternatives to PostSharp.

In order to intercept property getter calls,
Follow these steps:
  1. Download the latest version of PostSharp
  2. Add the PostSharp reference to your project.
  3. Create an Aspect (custom attribute to intercept a call)
    using System;
    using PostSharp.Aspects;
    
    namespace AOPSample
    {
        [Serializable]
        [AttributeUsage(AttributeTargets.Property)]
        public sealed class LocalizationAttribute : LocationInterceptionAspect
        {
            // Invoked at runtime whenever someone gets the value of the field or property.
            public override void OnGetValue(LocationInterceptionArgs args)
            {
                if (LocalizationHelper.MustLocalize && LocalizationHelper.LocalizationIsOn)
                {
                    base.OnGetValue(args);
    
                    // do something with your string, I add some fake localization
                    string s = args.Value as string;
                    s = s + "_en-GB";
                    args.Value = s;
                }
                else
                {
                    base.OnGetValue(args);
                }
            }
    
    
        }
    }
    
    

  4. Annotate the properties with your new aspect attribute where you want to intercept calls.
    ...
       [LocalizationAttribute]
       public virtual string Name { get; set; }
     ...
    

Now, each time the property is called your OnGetValue interception method is called.

No comments: