Search code examples
postsharp

PostSharp: Method *** should be annotated with a selector custom attribute because it is a master handler


This code throw error: Method ...OnEntry(...) should be annotated with a selector custom attribute because it is a master handler.

[PSerializable]
public class LogRequestAttribute : MethodLevelAspect, IAspectProvider {
    public IEnumerable<AspectInstance> ProvideAspects(object target) {
        yield return new AspectInstance( target, new LogPlainRequest() );
    }
}

[PSerializable]
public class LogPlainRequest : IMethodLevelAspect {
    public void RuntimeInitialize(MethodBase method) {
    }
    [OnMethodEntryAdvice]
    public void OnEntry(MethodExecutionArgs args) {
    }
}

What is it error meaning? And what is wrong?


Solution

  • You can combine several related advices into one group (e.g. OnEntry, OnExit). This is what OnMethodBoundaryAspect does for you automatically. After you've grouped the advices you need to designate one of them as a "master advice". The properties and the pointcut of the group must be set on the master advice.

    The pointcut assigned to the master advice acts as a selector of the advice's target element. The SelfPointcut, for example, simply selects the target of the aspect as the target of the advice. You can find more info and different pointcut kinds in the docs: https://doc.postsharp.net/advices

    In the example above you can apply the [SelfPointcut] attribute to the OnEntry method to get rid of the error message.

    [PSerializable]
    public class LogPlainRequest : IMethodLevelAspect {
        public void RuntimeInitialize(MethodBase method) {
        }
    
        [OnMethodEntryAdvice]
        [SelfPointcut]
        public void OnEntry(MethodExecutionArgs args) {
        }
    }