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:
- Download the latest version of PostSharp
- Add the PostSharp reference to your project.
- 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); } } } }
- 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:
Post a Comment