Skip to content

[Blazor] Support serialization extensibility for declarative persistent component state #60716

@javiercn

Description

@javiercn
Member

Currently we only serialize things as json. Ideally, we need an interface or something that you can implement (or pass as a parameter in the attribute) to provide a custom serialization mechanism.

The interface will be something like

public interface IPersistentComponentStateSerializer
{
    Task Persist(Type type, object instance, IBufferWriter buffer);
    void Restore(Type type, ReadOnlySequence<byte> data);
}
  • Restore needs to be synchronous to avoid tearing on the UI.
  • We don't want byte[] based APIs, as we want to minimize additional allocations if possible and we don't want to give the serializer the responsibility of allocating buffers.

Implementation Plan for Serialization Extensibility in Persistent Component State

Sample Registration

// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

// Register custom serializer as Singleton
builder.Services.AddSingleton<IPersistentComponentStateSerializer<User>, CustomUserSerializer>();

var app = builder.Build();

Task Checklist

1. Define the Serializer Interface

  • Create IPersistentComponentStateSerializer interface
    Define PersistAsync(T value, IBufferWriter writer, CancellationToken cancellationToken) method
    Define Restore(ReadOnlySequence data) method (synchronous)
    Add appropriate XML documentation for the interface and methods

2. Update PooledArrayBufferWriter Integration

  • Ensure PooledArrayBufferWriter from /src/Shared/PooledArrayBufferWriter.cs is accessible
    Verify compatibility with IBufferWriter interface for the Persist method
    Add any necessary using statements or references

3. Modify Persistent State Value Provider

  • Update the persistent state value provider to attempt DI resolution of IPersistentComponentStateSerializer
    Implement fallback logic to use default JSON serialization when no custom serializer is found
    Handle type-specific serializer resolution
    Ensure proper error handling for serializer resolution failures

5. Maintain Backward Compatibility

  • Ensure existing JSON serialization continues to work unchanged
    Verify no breaking changes to existing persistent component state APIs

6. Add Tests

  • Unit tests for the new interface implementation

Metadata

Metadata

Labels

area-blazorIncludes: Blazor, Razor Components

Type

No type

Projects

No projects

Relationships

None yet

    Participants

    @javiercn

    Issue actions

      [Blazor] Support serialization extensibility for declarative persistent component state · Issue #60716 · dotnet/aspnetcore