Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 447
krisg Avatar asked Mar 04 '10 04:03

krisg


2 Answers

You have to use:

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

Or:

[Test(AttributeInheritance=MulticastInheritance.Multicast] 
public interface ISystemService 
like image 126
Gael Fraiteur Avatar answered Sep 27 '22 17:09

Gael Fraiteur


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.

like image 27
Dmytrii Nagirniak Avatar answered Sep 27 '22 16:09

Dmytrii Nagirniak