views:

140

answers:

2

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?

+1  A: 

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
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
This applies to 'Custom Attribute Multicasting'. I provided the link in the answer.
Dmytrii Nagirniak
+2  A: 

You have to use:

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

Or:

[Test(AttributeInheritance=MulticastInheritance.Multicast] 
public interface ISystemService 
Gael Fraiteur
The second one worked.Thanks.
krisg