Adding Aspects to Code

An aspect has no effect until it is applied to some element of code. PostSharp provides multiple ways to add aspects to your code.

Applying Aspects to Multiple Elements of Code Declaratively

In many situations, you want to apply the same aspect to many elements of code. For instance, you may need to add tracing or performance monitoring to all public methods of a namespace. Since there may be hundreds of affected methods, you don't want to add a custom attribute to all of them.

Thanks to an extension of semantics of custom attributes named multicast custom attribute (MulticastAttribute), it is easy to apply an aspect to multiple elements of code using a single line of code.

For details, see Adding Aspects Declaratively Using Attributes and Understanding Aspect Inheritance.

Applying Aspects to Multiple Elements of Code Imperatively

If declarative features of MulticastAttribute are not sufficient for your case, you can select elements of code imperatively. For instance, you can develop complex filters based on System.Reflection or read information from an XML file.

There are two ways you can implement imperative selection aspect targets:

Filtering Out Using CompileTimeValidate

To filter out elements of codes that have been selected by MulticastAttribute, you can implement the method CompileTimeValidate(Object) of your aspect and silently return false if the candidate target is not appropriate. .

For instance, the following aspect will apply only on security-critical methods.

C#
using System;
using System.Reflection;
using PostSharp.Aspects;
using PostSharp.Serialization;

namespace Samples2
{
    [PSerializable]
    public sealed class TraceSecurityCriticalAttribute : OnMethodBoundaryAspect
    {
        // Select only security-critical methods.
        public override bool CompileTimeValidate(MethodBase method)
        {
            return method.IsSecurityCritical;
        }

        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("On Entry");
        }
    }
}

See Validating Aspect Usage for details.

Adding Aspect Instances Using IAspectProvider

If you have to implement more complex rules to select the target of aspects, you can create another aspect that will do nothing else than adding aspect instances to your code. This aspect must implement the interface IAspectProvider and will typically derive from AssemblyLevelAspect or TypeLevelAspect.

Tip Tip

Use ReflectionSearch to perform complex queries over System.Reflection.