Open sandboxFocusImprove this doc

LA0119: Aspect Class Is Not Serializable

Severity Error
Reported by PostSharp
Message Aspect type "<AspectType>" must be annotated with [PSerializable].

Cause

PostSharp creates the aspect instances at build time and serializes them into the assembly, so that the run time gets them back with the state they had after build-time initialization. It chooses the serializer from the aspect class:

PostSharp reports LA0119 when the aspect class has none of them. The message is reported on the aspect class <AspectType>, for each aspect class that needs an instance at run time.

In the following example, the [Log] aspect has no serialization attribute.

using System;
using PostSharp.Aspects;

namespace Errors.LA0119_Error;

// The aspect class has no [PSerializable] attribute, so PostSharp cannot serialize its instances.
public class LogAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry( MethodExecutionArgs args )
    {
        Console.WriteLine( $"Entering {args.Method.Name}." );
    }
}

public class OrderService
{
    [Log]
    public void PlaceOrder( string product )
    {
        Console.WriteLine( $"Order placed for {product}." );
    }
}

public static class Program
{
    public static void Main()
    {
        new OrderService().PlaceOrder( "Coffee" );
    }
}
error LA0119: LA0119_Error.cs(7,14): Aspect type "Errors.LA0119_Error.LogAttribute" must be annotated with [PSerializable].

Resolution

Do not use [SerializableAttribute] instead: it requires the binary serializer of .NET, which PostSharp does not allow by default, and PostSharp reports LA0206. See BinaryFormatter Security.

In the following example, the aspect class has the [PSerializableAttribute] attribute.

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

namespace Errors.LA0119_Fixed;

// PostSharp serializes the instances of the aspect at build time.
[PSerializable]
public class LogAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry( MethodExecutionArgs args )
    {
        Console.WriteLine( $"Entering {args.Method.Name}." );
    }
}

public class OrderService
{
    [Log]
    public void PlaceOrder( string product )
    {
        Console.WriteLine( $"Order placed for {product}." );
    }
}

public static class Program
{
    public static void Main()
    {
        new OrderService().PlaceOrder( "Coffee" );
    }
}
Entering PlaceOrder.
Order placed for Coffee.

See Also

Reference

PSerializableAttribute
MsilAspectSerializer
SerializerType

Other Resources

Understanding Aspect Serialization
BinaryFormatter Security