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?

krisg
  • 796
  • 1
  • 9
  • 24

2 Answers2

8

You have to use:

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

Or:

[Test(AttributeInheritance=MulticastInheritance.Multicast] 
public interface ISystemService 
Gael Fraiteur
  • 6,759
  • 2
  • 24
  • 31
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.

Dmytrii Nagirniak
  • 23,696
  • 13
  • 75
  • 130
  • 1
    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? – krisg Mar 04 '10 at 04:48
  • This applies to 'Custom Attribute Multicasting'. I provided the link in the answer. – Dmytrii Nagirniak Mar 04 '10 at 05:24
  • @Dmitrii, the links are broken. Did you meant http://doc.sharpcrafters.com/postsharp-2.0/##PostSharp-2.0.chm/html/42748720-e440-487a-a332-4c6b447d349c.htm and http://doc.sharpcrafters.com/postsharp-2.0/##PostSharp-2.0.chm/html/T_PostSharp_Extensibility_MulticastAttribute.htm – Michael Freidgeim Nov 21 '11 at 11:18
  • 1
    At the time of the answer the links worked. Feel free to update my answer with the new links. I already don't remember :) – Dmytrii Nagirniak Nov 21 '11 at 21:24