Search code examples
c#c#-4.0postsharp

PostSharp Interface Method Attribute


Imagine that I have the following:

public interface IMyInterface {
    void DoSomething();
}

public class MyClass: IMyInterface {
    public void DoSomething() {
        // do something
    }
}

Then, I want to create a method attribute like so:

[PSerializable]
[AttributeUsage(AttributeTargets.Method)]
public class NotNullAttribute : MethodImplementationAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        throw new NullReferenceException();
    }
}

Now, I know that I can apply this to the class method.

However, I want to be able to do something like the following:

public interface IMyInterface {
    [NotNull]
    void DoSomething();
}

Then, all classes that implement this method have the interceptor applied. Unfortunately, this gives me an error at compile time.

Is this possible? I attempted to find answers in the docs, but I've been unsuccessful.

If this is possible, can someone please help me understand how to accomplish this?


Solution

  • I got it working...

    I was missing an attribute on both the attribute definition and the abstract method.

    Working example:

    [PSerializable]
    [MulticastAttributeUsage(MulticastTargets.Method, TargetMemberAttributes = MulticastAttributes.Instance)]
    [AttributeUsage(AttributeTargets.Method)]
    public class NotNullAttribute : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            throw new NullReferenceException();
        }
    }
    

    And how it's used:

    public interface IMyInterface {
        [NotNull(AttributeInheritance = MulticastInheritance.Multicast)]
        void DoSomething();
    }
    
    public class MyClass: IMyInterface {
        public void DoSomething() {
            // do something
        }
    }