Search code examples
c#interfaceattributespostsharp

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 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?


Solution

  • You have to use:

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

    Or:

    [Test(AttributeInheritance=MulticastInheritance.Multicast] 
    public interface ISystemService