Open sandboxFocusImprove this doc

LA0078: Imported Member Field Is Static

Severity Error
Reported by PostSharp
Message Field "<Field>" cannot be annotated by [ImportMember] because it is static.

Cause

An aspect imports a member of its target class with a field annotated with ImportMemberAttribute. PostSharp assigns this field in each instance of the aspect, with delegates bound to the target object of this instance. A static field is shared by all the instances of the aspect, so it cannot hold the member of each target object, and PostSharp reports LA0078.

In the following example, the [TraceCreation] aspect imports the Describe method of Customer into a static field.

using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;

namespace Errors.LA0078_Error;

[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
    // A static field cannot hold a member of each instance of the target class.
    [ImportMember( "Describe", IsRequired = true )]
    public static Func<string>? Describe;

    public override void RuntimeInitializeInstance()
    {
        Console.WriteLine( $"Created {Describe!()}" );
    }
}

[TraceCreation]
public class Customer
{
    public string Name { get; set; } = "Alice";

    public string Describe() => $"customer {this.Name}";
}

public static class Program
{
    public static void Main()
    {
        _ = new Customer();
    }
}
error LA0078: LA0078_Error.cs(13,33): Field "Errors.LA0078_Error.TraceCreationAttribute.Describe" cannot be annotated by [ImportMember] because it is static.

Resolution

Remove the static modifier of the field, and access the field through the instance of the aspect.

using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;

namespace Errors.LA0078_Fixed;

[PSerializable]
public class TraceCreationAttribute : InstanceLevelAspect
{
    // An instance field receives the Describe method of the target object.
    [ImportMember( "Describe", IsRequired = true )]
    public Func<string>? Describe;

    public override void RuntimeInitializeInstance()
    {
        Console.WriteLine( $"Created {this.Describe!()}" );
    }
}

[TraceCreation]
public class Customer
{
    public string Name { get; set; } = "Alice";

    public string Describe() => $"customer {this.Name}";
}

public static class Program
{
    public static void Main()
    {
        _ = new Customer();
    }
}
Created customer Alice

See Also

Reference

ImportMemberAttribute

Other Resources

Accessing Members of the Target Class