Skip to content

Complete example in Orleans / Serialization / Surrogates #44720

@egil

Description

@egil

Describe the issue or suggestion

@ReubenBond helped set up this sample that demonstrates a more complex example of creating surrogates in Orleans serialization.

The docs could benefit from including a variant of this example in https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/serialization?pivots=orleans-7-0#surrogates-for-serializing-foreign-types

// Foreign types
public record Foo<T>(string Name, T Payload) where T : Bar;
public record Bar(Baz Baz, string Something);
public record Baz(string Hi);
public record BarY(string Content, Baz Baz, string Something) : Bar(Baz, Something);

// Surrogates
[GenerateSerializer, Immutable]
public readonly record struct FooSurrogate<T>(string Name, T Payload) where T : Bar;

[GenerateSerializer, Immutable]
public readonly record struct BarSurrogate(Baz Baz, string Something);

[GenerateSerializer, Immutable]
public readonly record struct BazSurrogate(string Hi);

[GenerateSerializer, Immutable]
public readonly record struct BarYSurrogate(string Content, Baz Baz, string Something);

// Converters
public sealed class FooConverter<T> : IConverter<Foo<T>, FooSurrogate<T>> where T : Bar
{
    public Foo<T> ConvertFromSurrogate(in FooSurrogate<T> surrogate) => new(surrogate.Name, surrogate.Payload);
    public FooSurrogate<T> ConvertToSurrogate(in Foo<T> value) => new(value.Name, value.Payload);
}

public sealed class BarConverter : IConverter<Bar, BarSurrogate>
{
    public Bar ConvertFromSurrogate(in BarSurrogate surrogate) => new(surrogate.Baz, surrogate.Something);
    public BarSurrogate ConvertToSurrogate(in Bar value) => new (value.Baz, value.Something);
}

public sealed class BazConverter : IConverter<Baz, BazSurrogate>
{
    public Bar ConvertFromSurrogate(in BazSurrogate surrogate) => new(value.Hi);
    public BarSurrogate ConvertToSurrogate(in Baz value) => new (value.Hi);
}

public sealed class BarYConverter : IConverter<BarY, BarYSurrogate>
{
    public BarY ConvertFromSurrogate(in BarYSurrogate surrogate) => new(surrogate.Content, surrogate.Baz, surrogate.Something);
    public BarYSurrogate ConvertToSurrogate(in BarY value) => new (value.Content, value.Baz, value.Something);
}

Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions