Applying an Attribute to an Interface Using PostSharp

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

I assumed that it would look something like this:

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

However, when I apply it to an interface, as shown below, the OnEntry / OnExit code in the attribute never opens when the method is called in a class that implements the interface:

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

If I applied the attribute inside the implementation class itself, as shown below, it works fine:

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

What am I missing / doing wrong?

+7
c # interface attributes postsharp
source share
2 answers

You should use:

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

Or:

 [Test(AttributeInheritance=MulticastInheritance.Multicast] public interface ISystemService 
+7
source share

What am I missing / doing wrong?

the interface has no implementation, so it cannot execute any “OnEntry / OnExit code”.

I believe you should inherit a class.


In addition, you can use the Multicast attribute , but you need to inherit from MulticastAttribute .

+1
source share

All Articles