Search code examples
c#.netpostsharp

Using postSharp how to capture all method entry and exit event at class level?


Using postsharp I can capture entry and exit event for a method when I apply my custom attribute on that method. But is there any way to capture this entry and exit of a method when I apply the attribute on Class level instead of a method level? Such as, when I apply the attribute, it should capture entry and exit of any method under that class. Below is the sample code for method level capture

public class CustomAttr: OnMethodBoundaryAspect
    {
        [NonSerialized]
        public override void OnEntry(MethodExecutionArgs args)
        {
            //do something
        }

        public override void OnSuccess(MethodExecutionArgs args)
        {
            //do something
        }
    }

Solution

  • Yes, this is called "attribute multicasting". There are several ways to do that, all of which are documented at https://doc.postsharp.net/applying-aspects.

    The one you're asking for is documented at https://doc.postsharp.net/attribute-multicasting#all-members as mentioned in the comment by @Peter Bons and it works exactly as you expect - you apply the attribute on the class and all methods of the class will get enhanced by the respective aspect. See the documentation for how to filter out some of the methods, e.g. by name or visibility.