0

Can I specify that a PostSharp aspect will be applied just to all public methods of child classes of a given class?

I mean, I have ClassA and want that an OnMethodBoundaryAspect be applied just to public methods defined in classes that inherited from the ClassA.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123

1 Answers1

0

You need to use AttributeInheritance property of MulticastAttribute to control that behavior.

  • MulticastInheritance.None is the default behavior. Aspect is not inherited by derived classes.
  • MulticastInheritance.Strict makes derived classes inherit the aspect on base class members, i.e. on overridden methods.
  • MulticastInheritance.Multicast makes derived classes to completely inherit the aspect, i.e. as if you have specified the aspect on the derived class.

Then, you need to use AttributeTargetMemberAttributes of MulticastAttribute to specify on which members the attribute should be applied. In your case this would be AttributeTargetMemberAttributes = MulticastAttributes.Public.

Last, you need to force PostSharp not to apply the attribute to the base class itself, you may use AttributeExclude property on another attribute instance to disable the aspect on specific occasions.

So, "just to all public methods of child classes of a given class" would be satisfied by the following:

[MyAspect(AttributeInheritance = MulticastInheritance.Multicast, AttributeTargetMemberAttributes = MulticastAttributes.Public)]
[MyAspect(AttributeExclude = true)]
public class ClassA
{
    //...
}

Note that this is compile-time behavior and you need to run PostSharp on all projects that are deriving from the base class in order for it to work as intended. If you derived from the class in a project not enhanced by PostSharp, no aspect behavior will be inherited.

Daniel Balas
  • 1,805
  • 1
  • 15
  • 20
  • Thanks for your comment Daniel, but what at least I misunderstand what you said, with none of those options I get what I want: apply the attribute to *"just to public methods defined in classes that inherited from" a given class* –  Jan 07 '15 at 14:41
  • @gsc-frank The question was not entirely clear. I have updated my answer to match it's intended meaning more closely (hopefully). – Daniel Balas Jan 07 '15 at 16:05