130 likes | 480 Views
PostSharp – Aspect-Oriented Programming in C#. Stephen Hammack. Overview. C# is an object-oriented programming language with elements of other programming paradigms Imperative, functional, event-driven, etc. Does not include aspect-oriented programming
E N D
PostSharp – Aspect-Oriented Programming in C# Stephen Hammack
Overview • C# is an object-oriented programming language with elements of other programming paradigms • Imperative, functional, event-driven, etc. • Does not include aspect-oriented programming • PostSharp is a Visual Studio plugin that adds aspect-oriented programming to C# • This plugin utilizes classes and attributes to define and apply aspects • After Visual Studio compiles the program to MSIL, PostSharp runs a post-processor to apply the aspects • Only requires the PostSharp libraries at run-time
OnMethodBoundaryAspect • Aspect class for injecting behaviors on methods • Four advices: OnEntry, OnExit, OnSuccess, and OnException • All advices have MethodExecutionArgsas the argument • Provides access to the intercepted method’s state and the instance it belongs to • Can change return value and alter what happens when the advice returns • Also holds an object to be passed between the advices
LocationInterceptionAspect • Aspect class for injecting behaviors on properties and fields • Two advices: OnGetValue and OnSetValue • Both advices have LocationInterceptionArgs as the argument • Provides access to the value of the property or field • Can utilize proceed to run the default get/set • Note: in C#, properties can specify custom get/set methods
Additional Aspect Features • Can inject behaviors to events • Events are native C# constructs for notifying observers in event-driven design • Able to introduce properties, methods, and interfaces to classes through the aspect • Mark things that are to be introduced from an aspect with the appropriate attribute
Applying Aspects to Many Targets • Similar to pointcuts, PostSharp can apply aspects to many targets through multicasting, rather than using one attribute per target • Uses a different syntax than AspectJpointcuts • Assembly attributes are added outside of any class or namespace, often in its own file, to indicate what to apply the aspects to • Examples:
Built-in Aspect Implementations • Non-free versions of PostSharp (and the trial) include commonly used cases for Aspect-Oriented programming • Automatic implementation of INotifyPropertyChanged • Commonly used to synchronize program model objects with the user interface • Detailed logging and tracing • Applying exception handling across the program • Simplified parameter assertion (e.g. non-null) • Many others