Search code examples
postsharp

Can I use reflection to find aspects produced by multicast?


I have a case where an aspect CanBeDependedUpon on class A is multicast to the properties of class A. However when inspecting class A from aspect DependsOn, I do not find CanBeDependedUpon on the properties of Y. Is this correct PostSharp behavior?

[CanBeDependedUpon]
class A
{
    public bool Foo
    {
        get;
        set;
    }

    [DependsOn("Foo")]
    public bool Bar
    {
        get;
        set;
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property, AllowMultiple = true)]
[MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Struct | MulticastTargets.Property, PersistMetaData = true, AllowMultiple = true)]
class CanBeDependedUpon : Aspect
{
}

class DependsOn : Aspect
{
    private string _target;

    public DependsOn(string target)
    {
        _target = target;
    }

    public override bool CompileTimeValidate(object target)
    {
        //validate that the target property exists and is annotated with X.
        return base.CompileTimeValidate(target);
    }
}

Solution

  • By default, PostSharp removes the attribute once the aspect has been applied to your code. You can explicitly instruct PostSharp to retain the attributes if you want to look them up using reflection.

    For this, you need to apply MulticastAttributeUsage attribute to your class and set PersistMetaData to true.

    [MulticastAttributeUsage( MulticastTargets.Class, PersistMetaData = true )]
    

    This use case is documented here: http://doc.postsharp.net/multicast-reflection