Applying an attribute to an interface using PostSharp
Asked Answered
C

2

8

I want to be able to apply an attribute to an interface so that every method in any class that implements that interface will have the attribute applied to it.

I assumed it would look something like this:

[Serializable]
[AttributeUsage(AttributeTargets.All, Inherited = true)]
public sealed class TestAttribute : OnMethodBoundaryAspect
{
    ...
}

Yet when i apply it to an interface like below, the OnEntry/OnExit code in the attribute is never accessed when the method is called in the class implementing the interface:

[Test]
public interface ISystemService
{
    List<AssemblyInfo> GetAssemblyInfo();
}

If i apply the attribute within the implementing class itself, as below, it works fine:

[Test]
public class SystemService : ISystemService
{
    ...
}

What am i missing/doing wrong?

Cichlid answered 4/3, 2010 at 4:6 Comment(0)
T
8

You have to use:

[MulticastAttributeUsage(..., Inheritance=MulticastInheritance.Multicast)]
public sealed class TestAttribute : OnMethodBoundaryAspect 

Or:

[Test(AttributeInheritance=MulticastInheritance.Multicast] 
public interface ISystemService 
Topple answered 4/3, 2010 at 15:44 Comment(0)
D
1

What am i missing/doing wrong?

interface has no implementation, thus cannot execute any ' OnEntry/OnExit code'.

I believe you should inherit from a class.


Additionally you can Multicast the attribute, but you need to inherit from MulticastAttribute.

Diapause answered 4/3, 2010 at 4:21 Comment(4)
Quoting the PostSharp documentation: "you can put a custom attribute on an interface and have it implicitly applied on all classes implementing that interface." Ergo, if i apply it to the class and it applies it to all the methods/properties therein, then by the above statement, applying it to an interface should do the same. Right?Cichlid
This applies to 'Custom Attribute Multicasting'. I provided the link in the answer.Diapause
@Dmitrii, the links are broken. Did you meant doc.sharpcrafters.com/postsharp-2.0/##PostSharp-2.0.chm/html/… and doc.sharpcrafters.com/postsharp-2.0/##PostSharp-2.0.chm/html/…Whacking
At the time of the answer the links worked. Feel free to update my answer with the new links. I already don't remember :)Diapause

© 2022 - 2024 — McMap. All rights reserved.