Search code examples
postsharp

How to add attributes to aspect/compiler-generated property?


I'm adding a property to a class and have my Aspect set up like this:

[PSerializable]
public class MyAspect : InstanceLevelAspect
{
    [MaxLength(100)]
    [IntroduceMember]
    public string MyProp { get; set; }
}

My target class is then decorated with the [MyAspect] attribute.

When Postsharp adds the MyProp property to the target class, it does not include the MaxLength attribute on the generated property. The property in the Aspect class includes it, but the property added to my target class does not.

I need the attributes specified for the property in the aspect definition to be added to the property added to my target class. How can I add the attributes to the generated property?


Solution

  • To intruct PostSharp to copy the attribute, you need to use [CopyCustomAttributes] (doc), so your aspect would look like this:

    [PSerializable]
    public class MyAspect : InstanceLevelAspect
    {
        [MaxLength(100)]
        [IntroduceMember]
        [CopyCustomAttributes(typeof(MaxLengthAttribute))]
        public string MyProp { get; set; }
    }