Search code examples
postsharp

Aspect on class that will inspect all public methods


Looking for easier approach for exception handling.

I can do OnExceptionAspect for the purpose, though this will require explicit attributing to intended method.

Is there an easier way like by attributing/tagging at class level, it will monitor/inspect/inject all public method on-exception-thrown ?

As such, I only need to explicit tag the aspect at the class level, any public methods within it will auto-subscribe the aspect feature.


Solution

  • You can put OnExceptionAspect to any class. Then all it's methods (public, private, protected) will be decorated by the aspect.

    OnExceptionAspect can be put even on assembly level and it is possible to select on which classes in which namespaces will be the aspect "multicasted". For example:

    [assembly: MyOnException(AttributeTargetTypes = "MyNamespace.*",
        AttributeTargetTypeAttributes = MulticastAttributes.Public,
        AttributeTargetMemberAttributes = MulticastAttributes.Public)]
    

    multicasts MyOnException aspect to all public methods in all public classes in MyNamespace (and all sub-namespaces).