Annotating an Object Model programmatically

There are times where you cannot or don't want to add custom attributes manually.

For instance, you cannot add any custom attribute to an auto-generated field backing a XAML element. The WPF designer generates C# code from your XAML files and stores them in i.g.cs files well hidden in the obj folder. You cannot modify these files directly.

Another scenario is when you have a large amount of fields and don't want to annotate each of them individually.

Field rules allow you to annotate a field as a child or a reference programmatically, without adding a custom attribute to each field manually.

In the following example, let's consider a class where PostSharp shows an error message COM002: “Field/property InvoiceLine.product must be annotated with a custom attribute [Child], [Reference] or [Parent].”

public class InvoiceLine
  private Product product;

  public decimal Amount { get; set; }

To automatically mark all fields as references by default:

  1. Create a class inherited from the FieldRule class.

    public class RefererenceFieldRule : FieldRule
  2. Override the GetRelationshipInfo(FieldInfo) method. PostSharp calls the GetRelationshipInfo(FieldInfo) method for each field that is not annotated with the ChildAttribute, ReferenceAttribute or ParentAttribute custom attribute. The GetRelationshipInfo(FieldInfo) method allows you to specify the field relationship by returning a RelationshipInfo instance.

    public override RelationshipInfo? GetRelationshipInfo(FieldInfo field)
        return new RelationshipInfo(RelationshipKind.None, RelationshipKind.Reference);
  3. Decorate your project’s assembly with a RegisterFieldRuleAttribute custom attribute to activate your field rule.

    [assembly: RegisterFieldRule(typeof(RefererenceFieldRule))]
    Caution note Caution

    You have to mark each project assembly to make your FieldRule active in the whole solution.

Now PostSharp considers all fields without any Parent-Child annotation as a reference and doesn’t show any error for the product field.

Note Note

PostSharp has two built-in rules: one rule for auto-generated WinForms fields and one rule for auto-generated XAML fields.

<Window x:Class="WpfApp.MainWindow"
        <Button x:Name="myButton" />

In this example the WPF designer generates a myButton field to a MainWindow class. Both the myButton field and the MainWindow class are indirectly inherited from System.Windows.Controls.Control. The built-in rule annotates the myButton field as a reference automatically.

See Also