From b2979bbed985f543d6194006e1ab61206bb4cb75 Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Mon, 28 Sep 2026 18:00:36 -0600 Subject: [PATCH 1/3] Add per-call SerializationContext overloads to core (de)serialize methods Adds overloads to the 8 core Serialize/Deserialize(Object)(Async) methods over MessagePackWriter/Reader and PipeWriter/Reader that take a SerializationContext in place of the CancellationToken. The cancellation token comes from the context. Existing overloads delegate to shared private cores passing StartingContext. Sync cores initialize the context in place by ref to avoid an extra copy of the large struct. New overloads carry [OverloadResolutionPriority(-1)] so an explicit 'default' argument still binds to the CancellationToken overloads. A context already initialized for an in-flight operation (e.g. one handed to a converter) is rejected with ArgumentException. Adds a protected CreateSerializationContext(ITypeShapeProvider, SerializationContext) overload; library code no longer calls the overload that implicitly uses StartingContext. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docfx/docs/custom-converters.md | 16 + samples/cs/CustomConverters.cs | 15 + .../MessagePackSerializer.cs | 580 ++++++++++++------ .../SerializationContext.cs | 27 + .../PerCallSerializationContextTests.cs | 291 +++++++++ 5 files changed, 746 insertions(+), 183 deletions(-) create mode 100644 test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs diff --git a/docfx/docs/custom-converters.md b/docfx/docs/custom-converters.md index 5c23bde1..14027a28 100644 --- a/docfx/docs/custom-converters.md +++ b/docfx/docs/custom-converters.md @@ -184,6 +184,22 @@ Modify state on an existing @Nerdbank.MessagePack.MessagePackSerializer by captu [!code-csharp[](../../samples/cs/CustomConverters.cs#ModifyStateOnSerializer)] +#### Per-call state + +When the state varies from one call to the next (e.g. per RPC message rather than per connection), creating a new @Nerdbank.MessagePack.MessagePackSerializer for each call is unnecessary. +Instead, pass a directly to one of the overloads that accepts one, such as . +These overloads use the supplied context instead of , and take their cancellation token from its property. +The context is typically derived from so that it retains any other settings on it: + +[!code-csharp[](../../samples/cs/CustomConverters.cs#PerCallState)] + +These overloads are available for , , and , for both generic and untyped (`*Object`) (de)serialization. +To (de)serialize with other inputs or outputs (e.g. a `byte[]` or ), wrap them in one of these types first. + +A converter must never pass its own to these top-level methods. +Doing so throws an . +Use to (de)serialize nested values instead. + ### Async converters @Nerdbank.MessagePack.MessagePackConverter`1 is an abstract class that requires a derived converter to implement synchronous @Nerdbank.MessagePack.MessagePackConverter`1.Write* and @Nerdbank.MessagePack.MessagePackConverter`1.Read* methods. diff --git a/samples/cs/CustomConverters.cs b/samples/cs/CustomConverters.cs index e5125e0e..c5a7ff79 100644 --- a/samples/cs/CustomConverters.cs +++ b/samples/cs/CustomConverters.cs @@ -475,6 +475,21 @@ MessagePackSerializer ModifySerializer(MessagePackSerializer serializer) return serializer; } } + + class PerCallState + { + void Serialize(MessagePackSerializer serializer, System.Buffers.IBufferWriter bufferWriter, SpecialType value, CancellationToken cancellationToken) + { + #region PerCallState + SerializationContext context = serializer.StartingContext with { CancellationToken = cancellationToken }; + context["ValueMultiplier"] = 5; + + MessagePackWriter writer = new(bufferWriter); + serializer.Serialize(ref writer, value, TypeShapeResolver.ResolveDynamicOrThrow(), context); + writer.Flush(); + #endregion + } + } } namespace CustomConverterFactory diff --git a/src/Nerdbank.MessagePack/MessagePackSerializer.cs b/src/Nerdbank.MessagePack/MessagePackSerializer.cs index e0840497..881b3052 100644 --- a/src/Nerdbank.MessagePack/MessagePackSerializer.cs +++ b/src/Nerdbank.MessagePack/MessagePackSerializer.cs @@ -161,6 +161,10 @@ public bool UseDiscriminatorObjects /// /// Gets the starting context to begin (de)serializations with. /// + /// + /// Overloads that accept a parameter (e.g. ) + /// use that context instead of this one, to support per-call state or settings. + /// public SerializationContext StartingContext { get; init; } = new(); /// @@ -217,25 +221,27 @@ internal bool DisableHardwareAcceleration /// public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeShape shape, CancellationToken cancellationToken = default) { - Requires.NotNull(shape); + SerializationContext context = this.StartingContext; + this.SerializeObjectCore(ref writer, value, shape, ref context, cancellationToken); + } - try - { - SerializationContext context = this.StartingContext; - context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); - try - { - this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.WriteObject(ref writer, value, context); - } - finally - { - context.End(); - } - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during serialization.", ex); - } + /// + /// Serializes an untyped value using a caller-supplied starting context. + /// + /// The msgpack writer to use. + /// The value to serialize. + /// The shape of the value to serialize. + /// + /// The context to start this operation with, used instead of . + /// Its is used to cancel the operation. + /// This is typically derived from using a expression. + /// + /// Thrown if belongs to a serialization operation that is already in progress, such as the context given to a converter. + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + this.SerializeObjectCore(ref writer, value, shape, ref startingContext, startingContext.CancellationToken); } /// @@ -248,25 +254,24 @@ public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeSh /// A cancellation token. public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape shape, CancellationToken cancellationToken = default) { - Requires.NotNull(shape); + SerializationContext context = this.StartingContext; + this.SerializeCore(ref writer, value, shape, ref context, cancellationToken); + } - try - { - SerializationContext context = this.StartingContext; - context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); - try - { - this.ConverterCache.GetOrAddConverterValue(shape).WriteCore(ref writer, value, ref context); - } - finally - { - context.End(); - } - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during serialization.", ex); - } + /// + /// Serializes a value using a caller-supplied starting context. + /// + /// The type to be serialized. + /// The msgpack writer to use. + /// The value to serialize. + /// The shape of . + /// + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + this.SerializeCore(ref writer, value, shape, ref startingContext, startingContext.CancellationToken); } /// @@ -281,25 +286,23 @@ public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape public object? DeserializeObject(ref MessagePackReader reader, ITypeShape shape, CancellationToken cancellationToken = default) { - Requires.NotNull(shape); + SerializationContext context = this.StartingContext; + return this.DeserializeObjectCore(ref reader, shape, ref context, cancellationToken); + } - try - { - SerializationContext context = this.StartingContext; - context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); - try - { - return this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.ReadObject(ref reader, context); - } - finally - { - context.End(); - } - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during deserialization.", ex); - } + /// + /// Deserializes an untyped value using a caller-supplied starting context. + /// + /// The msgpack reader to deserialize from. + /// The shape of the value to deserialize. + /// + /// The deserialized value. + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public object? DeserializeObject(ref MessagePackReader reader, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.DeserializeObjectCore(ref reader, shape, ref startingContext, startingContext.CancellationToken); } /// @@ -327,7 +330,7 @@ public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape public dynamic? DeserializeDynamicPrimitives(ref MessagePackReader reader, CancellationToken cancellationToken = default) { - using DisposableSerializationContext context = this.CreateSerializationContext(MsgPackPrimitivesWitness.GeneratedTypeShapeProvider, cancellationToken); + using DisposableSerializationContext context = this.CreateSerializationContextCore(MsgPackPrimitivesWitness.GeneratedTypeShapeProvider, this.StartingContext, cancellationToken); try { return PrimitivesAsDynamicConverter.Instance.Read(ref reader, context.Value); @@ -353,7 +356,7 @@ public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShape public object? DeserializePrimitives(ref MessagePackReader reader, CancellationToken cancellationToken = default) { - using DisposableSerializationContext context = this.CreateSerializationContext(MsgPackPrimitivesWitness.GeneratedTypeShapeProvider, cancellationToken); + using DisposableSerializationContext context = this.CreateSerializationContextCore(MsgPackPrimitivesWitness.GeneratedTypeShapeProvider, this.StartingContext, cancellationToken); try { return PrimitivesAsObjectConverter.Instance.Read(ref reader, context.Value); @@ -374,24 +377,24 @@ public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShapeThe deserialized value. public T? Deserialize(ref MessagePackReader reader, ITypeShape shape, CancellationToken cancellationToken = default) { - Requires.NotNull(shape); SerializationContext context = this.StartingContext; - context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); - try - { - try - { - return this.ConverterCache.GetOrAddConverterValue(shape).ReadCore(ref reader, ref context); - } - finally - { - context.End(); - } - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during deserialization.", ex); - } + return this.DeserializeCore(ref reader, shape, ref context, cancellationToken); + } + + /// + /// Deserializes a value using a caller-supplied starting context. + /// + /// The type of value to deserialize. + /// The msgpack reader to deserialize from. + /// The shape of . + /// + /// The deserialized value. + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public T? Deserialize(ref MessagePackReader reader, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.DeserializeCore(ref reader, shape, ref startingContext, startingContext.CancellationToken); } /// @@ -403,41 +406,36 @@ public void Serialize(ref MessagePackWriter writer, in T? value, ITypeShapeThe shape of the type, as obtained from an . /// A cancellation token. /// A task that tracks the async serialization. - public async ValueTask SerializeAsync(PipeWriter writer, T? value, ITypeShape shape, CancellationToken cancellationToken = default) - { - Requires.NotNull(writer); - Requires.NotNull(shape); + public ValueTask SerializeAsync(PipeWriter writer, T? value, ITypeShape shape, CancellationToken cancellationToken = default) + => this.SerializeCoreAsync(writer, value, shape, this.StartingContext, cancellationToken); - try - { - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); - MessagePackAsyncWriter asyncWriter = new(writer); - await this.ConverterCache.GetOrAddConverterValue(shape).WriteAsync(asyncWriter, value, context.Value).ConfigureAwait(false); - asyncWriter.Flush(); - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during serialization.", ex); - } + /// + /// Serializes a value using the given and a caller-supplied starting context. + /// + /// The type to be serialized. + /// The writer to use. + /// The value to serialize. + /// The shape of the type, as obtained from an . + /// + /// A task that tracks the async serialization. + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public ValueTask SerializeAsync(PipeWriter writer, T? value, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.SerializeCoreAsync(writer, value, shape, startingContext, startingContext.CancellationToken); } /// - public async ValueTask SerializeObjectAsync(PipeWriter writer, object? value, ITypeShape shape, CancellationToken cancellationToken = default) - { - Requires.NotNull(writer); - Requires.NotNull(shape); + public ValueTask SerializeObjectAsync(PipeWriter writer, object? value, ITypeShape shape, CancellationToken cancellationToken = default) + => this.SerializeObjectCoreAsync(writer, value, shape, this.StartingContext, cancellationToken); - try - { - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); - MessagePackAsyncWriter asyncWriter = new(writer); - await this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.WriteObjectAsync(asyncWriter, value, context.Value).ConfigureAwait(false); - asyncWriter.Flush(); - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during serialization.", ex); - } + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public ValueTask SerializeObjectAsync(PipeWriter writer, object? value, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.SerializeObjectCoreAsync(writer, value, shape, startingContext, startingContext.CancellationToken); } /// @@ -448,87 +446,35 @@ public async ValueTask SerializeObjectAsync(PipeWriter writer, object? value, IT /// The shape of the type, as obtained from an . /// A cancellation token. /// The deserialized value. - public async ValueTask DeserializeAsync(PipeReader reader, ITypeShape shape, CancellationToken cancellationToken = default) - { - Requires.NotNull(reader); - Requires.NotNull(shape); - - try - { - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); - MessagePackConverter converter = this.ConverterCache.GetOrAddConverterValue(shape); - - // Buffer up to some threshold before starting deserialization. - // Only engage with the async code path (which is slower) if we reach our threshold - // and more bytes are still to come. - if (this.MaxAsyncBuffer > 0) - { - ReadResult readResult = await reader.ReadAtLeastNoLOHAsync(this.MaxAsyncBuffer, cancellationToken).ConfigureAwait(false); - if (readResult.IsCompleted) - { - MessagePackReader msgpackReader = new(readResult.Buffer); - T? result = converter.Read(ref msgpackReader, context.Value); - reader.AdvanceTo(msgpackReader.Position); - return result; - } - else - { - reader.AdvanceTo(readResult.Buffer.Start); - } - } + public ValueTask DeserializeAsync(PipeReader reader, ITypeShape shape, CancellationToken cancellationToken = default) + => this.DeserializeCoreAsync(reader, shape, this.StartingContext, cancellationToken); - MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; - await asyncReader.ReadAsync().ConfigureAwait(false); - T? result2 = await converter.ReadAsync(asyncReader, context.Value).ConfigureAwait(false); - asyncReader.Dispose(); // only dispose this on success paths, since on exception it may throw (again) and conceal the original exception. - return result2; - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during deserialization.", ex); - } + /// + /// Deserializes a value from a using a caller-supplied starting context. + /// + /// The type of value to deserialize. + /// + /// The shape of the type, as obtained from an . + /// + /// The deserialized value. + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public ValueTask DeserializeAsync(PipeReader reader, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.DeserializeCoreAsync(reader, shape, startingContext, startingContext.CancellationToken); } /// - public async ValueTask DeserializeObjectAsync(PipeReader reader, ITypeShape shape, CancellationToken cancellationToken = default) - { - Requires.NotNull(reader); - Requires.NotNull(shape); - - try - { - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); - MessagePackConverter converter = this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow; + public ValueTask DeserializeObjectAsync(PipeReader reader, ITypeShape shape, CancellationToken cancellationToken = default) + => this.DeserializeObjectCoreAsync(reader, shape, this.StartingContext, cancellationToken); - // Buffer up to some threshold before starting deserialization. - // Only engage with the async code path (which is slower) if we reach our threshold - // and more bytes are still to come. - if (this.MaxAsyncBuffer > 0) - { - ReadResult readResult = await reader.ReadAtLeastNoLOHAsync(this.MaxAsyncBuffer, cancellationToken).ConfigureAwait(false); - if (readResult.IsCompleted) - { - MessagePackReader msgpackReader = new(readResult.Buffer); - object? result = converter.ReadObject(ref msgpackReader, context.Value); - reader.AdvanceTo(msgpackReader.Position); - return result; - } - else - { - reader.AdvanceTo(readResult.Buffer.Start); - } - } - - MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; - await asyncReader.ReadAsync().ConfigureAwait(false); - object? result2 = await converter.ReadObjectAsync(asyncReader, context.Value).ConfigureAwait(false); - asyncReader.Dispose(); // only dispose this on success paths, since on exception it may throw (again) and conceal the original exception. - return result2; - } - catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) - { - throw new MessagePackSerializationException("An error occurred during deserialization.", ex); - } + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + public ValueTask DeserializeObjectAsync(PipeReader reader, ITypeShape shape, SerializationContext startingContext) + { + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.DeserializeObjectCoreAsync(reader, shape, startingContext, startingContext.CancellationToken); } /// @@ -816,7 +762,7 @@ static void WriteJsonString(string value, TextWriter builder) Requires.NotNull(shape); this.ThrowIfPreservingReferencesDuringEnumeration(); - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, this.StartingContext, cancellationToken); MessagePackConverter converter = this.ConverterCache.GetOrAddConverterValue(shape); MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; @@ -889,12 +835,33 @@ static void WriteJsonString(string value, TextWriter builder) /// A cancellation token for the operation. /// The serialization context. /// + /// + /// The returned context is based on . + /// To start from a caller-supplied context instead (e.g. to support per-call state), use . + /// + /// /// Callers should be sure to always call when done with the context. + /// /// protected DisposableSerializationContext CreateSerializationContext(ITypeShapeProvider provider, CancellationToken cancellationToken = default) + => this.CreateSerializationContextCore(Requires.NotNull(provider), this.StartingContext, cancellationToken); + + /// + /// Creates a new serialization context that is ready to process a serialization job, based on a caller-supplied starting context. + /// + /// + /// + /// The serialization context. + /// + /// Callers should be sure to always call when done with the context. + /// + /// + [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. + protected DisposableSerializationContext CreateSerializationContext(ITypeShapeProvider provider, SerializationContext startingContext) { Requires.NotNull(provider); - return new(this.StartingContext.Start(this, this.ConverterCache, provider, cancellationToken)); + startingContext.ThrowIfInitialized(nameof(startingContext)); + return this.CreateSerializationContextCore(provider, startingContext, startingContext.CancellationToken); } /// @@ -923,7 +890,7 @@ protected DisposableSerializationContext CreateSerializationContext(ITypeShapePr { this.ThrowIfPreservingReferencesDuringEnumeration(); - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, this.StartingContext, cancellationToken); MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; await asyncReader.ReadAsync().ConfigureAwait(false); @@ -945,7 +912,7 @@ protected DisposableSerializationContext CreateSerializationContext(ITypeShapePr { this.ThrowIfPreservingReferencesDuringEnumeration(); - using DisposableSerializationContext context = this.CreateSerializationContext(shape.Provider, cancellationToken); + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, this.StartingContext, cancellationToken); SkipToPathViaExpression skipper = new(this, shape, context.Value); return skipper.NavigateToMember(ref reader, options.Path) switch @@ -955,6 +922,253 @@ protected DisposableSerializationContext CreateSerializationContext(ITypeShapePr }; } + /// + /// Starts a serialization job based on the given starting context. + /// + /// + /// The context to base the job on. + /// The cancellation token for the job. + /// The serialization context. + private DisposableSerializationContext CreateSerializationContextCore(ITypeShapeProvider provider, in SerializationContext startingContext, CancellationToken cancellationToken) + => new(startingContext.Start(this, this.ConverterCache, provider, cancellationToken)); + + /// + /// Serializes a value, initializing the given context in place to avoid copying it. + /// + /// + /// The starting context, which is initialized in place. +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + private void SerializeCore(ref MessagePackWriter writer, in T? value, ITypeShape shape, ref SerializationContext context, CancellationToken cancellationToken) +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + { + Requires.NotNull(shape); + + try + { + context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); + try + { + this.ConverterCache.GetOrAddConverterValue(shape).WriteCore(ref writer, value, ref context); + } + finally + { + context.End(); + } + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during serialization.", ex); + } + } + + /// + private void SerializeObjectCore(ref MessagePackWriter writer, object? value, ITypeShape shape, ref SerializationContext context, CancellationToken cancellationToken) + { + Requires.NotNull(shape); + + try + { + context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); + try + { + this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.WriteObject(ref writer, value, context); + } + finally + { + context.End(); + } + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during serialization.", ex); + } + } + + /// + /// Deserializes a value, initializing the given context in place to avoid copying it. + /// + /// + /// The starting context, which is initialized in place. +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + private T? DeserializeCore(ref MessagePackReader reader, ITypeShape shape, ref SerializationContext context, CancellationToken cancellationToken) +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + { + Requires.NotNull(shape); + context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); + try + { + try + { + return this.ConverterCache.GetOrAddConverterValue(shape).ReadCore(ref reader, ref context); + } + finally + { + context.End(); + } + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during deserialization.", ex); + } + } + + /// + /// Deserializes an untyped value, initializing the given context in place to avoid copying it. + /// + /// + /// The starting context, which is initialized in place. +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + private object? DeserializeObjectCore(ref MessagePackReader reader, ITypeShape shape, ref SerializationContext context, CancellationToken cancellationToken) +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + { + Requires.NotNull(shape); + + try + { + context.Initialize(this, this.ConverterCache, shape.Provider, cancellationToken); + try + { + return this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.ReadObject(ref reader, context); + } + finally + { + context.End(); + } + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during deserialization.", ex); + } + } + + /// + /// The context to base the job on. +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + private async ValueTask SerializeCoreAsync(PipeWriter writer, T? value, ITypeShape shape, SerializationContext startingContext, CancellationToken cancellationToken) +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + { + Requires.NotNull(writer); + Requires.NotNull(shape); + + try + { + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, startingContext, cancellationToken); + MessagePackAsyncWriter asyncWriter = new(writer); + await this.ConverterCache.GetOrAddConverterValue(shape).WriteAsync(asyncWriter, value, context.Value).ConfigureAwait(false); + asyncWriter.Flush(); + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during serialization.", ex); + } + } + + /// + private async ValueTask SerializeObjectCoreAsync(PipeWriter writer, object? value, ITypeShape shape, SerializationContext startingContext, CancellationToken cancellationToken) + { + Requires.NotNull(writer); + Requires.NotNull(shape); + + try + { + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, startingContext, cancellationToken); + MessagePackAsyncWriter asyncWriter = new(writer); + await this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow.WriteObjectAsync(asyncWriter, value, context.Value).ConfigureAwait(false); + asyncWriter.Flush(); + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during serialization.", ex); + } + } + + /// + /// The context to base the job on. +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + private async ValueTask DeserializeCoreAsync(PipeReader reader, ITypeShape shape, SerializationContext startingContext, CancellationToken cancellationToken) +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) + { + Requires.NotNull(reader); + Requires.NotNull(shape); + + try + { + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, startingContext, cancellationToken); + MessagePackConverter converter = this.ConverterCache.GetOrAddConverterValue(shape); + + // Buffer up to some threshold before starting deserialization. + // Only engage with the async code path (which is slower) if we reach our threshold + // and more bytes are still to come. + if (this.MaxAsyncBuffer > 0) + { + ReadResult readResult = await reader.ReadAtLeastNoLOHAsync(this.MaxAsyncBuffer, cancellationToken).ConfigureAwait(false); + if (readResult.IsCompleted) + { + MessagePackReader msgpackReader = new(readResult.Buffer); + T? result = converter.Read(ref msgpackReader, context.Value); + reader.AdvanceTo(msgpackReader.Position); + return result; + } + else + { + reader.AdvanceTo(readResult.Buffer.Start); + } + } + + MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; + await asyncReader.ReadAsync().ConfigureAwait(false); + T? result2 = await converter.ReadAsync(asyncReader, context.Value).ConfigureAwait(false); + asyncReader.Dispose(); // only dispose this on success paths, since on exception it may throw (again) and conceal the original exception. + return result2; + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during deserialization.", ex); + } + } + + /// + private async ValueTask DeserializeObjectCoreAsync(PipeReader reader, ITypeShape shape, SerializationContext startingContext, CancellationToken cancellationToken) + { + Requires.NotNull(reader); + Requires.NotNull(shape); + + try + { + using DisposableSerializationContext context = this.CreateSerializationContextCore(shape.Provider, startingContext, cancellationToken); + MessagePackConverter converter = this.ConverterCache.GetOrAddConverter(shape).ValueOrThrow; + + // Buffer up to some threshold before starting deserialization. + // Only engage with the async code path (which is slower) if we reach our threshold + // and more bytes are still to come. + if (this.MaxAsyncBuffer > 0) + { + ReadResult readResult = await reader.ReadAtLeastNoLOHAsync(this.MaxAsyncBuffer, cancellationToken).ConfigureAwait(false); + if (readResult.IsCompleted) + { + MessagePackReader msgpackReader = new(readResult.Buffer); + object? result = converter.ReadObject(ref msgpackReader, context.Value); + reader.AdvanceTo(msgpackReader.Position); + return result; + } + else + { + reader.AdvanceTo(readResult.Buffer.Start); + } + } + + MessagePackAsyncReader asyncReader = new(reader) { CancellationToken = cancellationToken }; + await asyncReader.ReadAsync().ConfigureAwait(false); + object? result2 = await converter.ReadObjectAsync(asyncReader, context.Value).ConfigureAwait(false); + asyncReader.Dispose(); // only dispose this on success paths, since on exception it may throw (again) and conceal the original exception. + return result2; + } + catch (Exception ex) when (ShouldWrapSerializationException(ex, cancellationToken)) + { + throw new MessagePackSerializationException("An error occurred during deserialization.", ex); + } + } + /// Thrown if is not . private void ThrowIfPreservingReferencesDuringEnumeration() { diff --git a/src/Nerdbank.MessagePack/SerializationContext.cs b/src/Nerdbank.MessagePack/SerializationContext.cs index 33e203a1..2e9a2f61 100644 --- a/src/Nerdbank.MessagePack/SerializationContext.cs +++ b/src/Nerdbank.MessagePack/SerializationContext.cs @@ -21,6 +21,10 @@ namespace Nerdbank.MessagePack; /// To modify the starting context on an existing serializer, you can use the with keyword to create a new serializer with the updated context. /// /// +/// +/// A context may also be supplied for an individual (de)serialization operation by passing it to an overload that accepts one, +/// such as . +/// [DebuggerDisplay($"Depth remaining = {{{nameof(MaxDepth)}}}")] public record struct SerializationContext { @@ -349,6 +353,29 @@ internal void Initialize(MessagePackSerializer owner, ConverterCache cache, ITyp this.referenceEqualityTracker?.SetSerializationContext(this); } + /// + /// Throws if this context belongs to a serialization operation that has already started. + /// + /// The name of the parameter that supplied this context. + /// Thrown if this context has already been initialized for a serialization operation. + /// + /// A context that a converter receives has been initialized for an in-progress operation. + /// Passing such a context to a top-level serializer method would start a new operation that + /// shares nothing with the original one (e.g. reference preservation), which is almost certainly a bug. + /// + internal readonly void ThrowIfInitialized(string paramName) + { + if (this.cache is not null || this.typeShapeProvider is not null || this.referenceEqualityTracker is not null || this.stringInterningCache is not null || this.MidSkipRemainingCount != 0) + { + Throw(paramName); + } + + [DoesNotReturn] + static void Throw(string paramName) => throw new ArgumentException( + "This context belongs to a serialization operation that is already in progress. Custom converters should never call top-level serializer methods. Instead, use the converter returned by SerializationContext.GetConverter to (de)serialize nested values, passing along the context it was given.", + paramName); + } + /// /// Responds to the conclusion of a serialization operation by recycling any relevant objects. /// diff --git a/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs new file mode 100644 index 00000000..f2a76de9 --- /dev/null +++ b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs @@ -0,0 +1,291 @@ +// Copyright (c) Andrew Arnott. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +/// +/// Tests for the (de)serialize overloads that accept a per-call . +/// +public partial class PerCallSerializationContextTests : MessagePackSerializerTestBase +{ + private const string MultiplierKey = "PerCallSerializationContextTests.Multiplier"; + + private static readonly ITypeShape ScaledShape = TypeShapeResolver.ResolveDynamicOrThrow(); + private static readonly ITypeShape OuterShape = TypeShapeResolver.ResolveDynamicOrThrow(); + + [Test] + public void Serialize_Deserialize_Generic() + { + SerializationContext context = this.CreateContext(multiplier: 3); + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, context); + writer.Flush(); + + AssertEncodedInt(sequence, 15); + + MessagePackReader reader = new(sequence); + Assert.Equal(new Scaled(5), this.Serializer.Deserialize(ref reader, ScaledShape, context)); + } + + [Test] + public void SerializeObject_DeserializeObject() + { + SerializationContext context = this.CreateContext(multiplier: 3); + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.SerializeObject(ref writer, new Scaled(5), ScaledShape, context); + writer.Flush(); + + AssertEncodedInt(sequence, 15); + + MessagePackReader reader = new(sequence); + Assert.Equal(new Scaled(5), this.Serializer.DeserializeObject(ref reader, ScaledShape, context)); + } + + [Test] + public async Task SerializeAsync_DeserializeAsync_Generic() + { + SerializationContext context = this.CreateContext(multiplier: 3); + + Pipe pipe = new(); + await this.Serializer.SerializeAsync(pipe.Writer, new Scaled(5), ScaledShape, context); + await pipe.Writer.FlushAsync(this.TimeoutToken); + await pipe.Writer.CompleteAsync(); + + Assert.Equal(new Scaled(5), await this.Serializer.DeserializeAsync(pipe.Reader, ScaledShape, context)); + } + + [Test] + public async Task SerializeObjectAsync_DeserializeObjectAsync() + { + SerializationContext context = this.CreateContext(multiplier: 3); + + Pipe pipe = new(); + await this.Serializer.SerializeObjectAsync(pipe.Writer, new Scaled(5), ScaledShape, context); + await pipe.Writer.FlushAsync(this.TimeoutToken); + await pipe.Writer.CompleteAsync(); + + Assert.Equal(new Scaled(5), await this.Serializer.DeserializeObjectAsync(pipe.Reader, ScaledShape, context)); + } + + [Test] + public async Task AsyncOverloads_WrittenBytesReflectContext() + { + Pipe pipe = new(); + await this.Serializer.SerializeAsync(pipe.Writer, new Scaled(5), ScaledShape, this.CreateContext(multiplier: 7)); + await pipe.Writer.FlushAsync(this.TimeoutToken); + await pipe.Writer.CompleteAsync(); + + ReadResult result = await pipe.Reader.ReadAsync(this.TimeoutToken); + AssertEncodedInt(result.Buffer, 35); + pipe.Reader.AdvanceTo(result.Buffer.End); + } + + [Test] + public void StartingContextIsIgnoredWhenContextIsSupplied() + { + SerializationContext serializerContext = this.Serializer.StartingContext; + serializerContext[MultiplierKey] = 2; + this.Serializer = this.Serializer with { StartingContext = serializerContext }; + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, this.CreateContext(multiplier: 10)); + writer.Flush(); + AssertEncodedInt(sequence, 50); + + // The CancellationToken overload continues to use StartingContext. + sequence.Reset(); + writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, this.TimeoutToken); + writer.Flush(); + AssertEncodedInt(sequence, 10); + } + + [Test] + public void DefaultLiteralBindsToCancellationTokenOverload() + { + SerializationContext serializerContext = this.Serializer.StartingContext; + serializerContext[MultiplierKey] = 4; + this.Serializer = this.Serializer with { StartingContext = serializerContext }; + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + + // This must compile without ambiguity, and use StartingContext (evident by the multiplier being applied). + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, default); + writer.Flush(); + AssertEncodedInt(sequence, 20); + + MessagePackReader reader = new(sequence); + Assert.Equal(new Scaled(5), this.Serializer.Deserialize(ref reader, ScaledShape, default)); + } + + [Test] + public void CancellationTokenComesFromContext() + { + CancellationTokenSource cts = new(); + cts.Cancel(); + SerializationContext context = this.CreateContext(multiplier: 1) with { CancellationToken = cts.Token }; + + Sequence sequence = new(); + Assert.Throws(() => + { + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, context); + }); + + Assert.Throws(() => + { + MessagePackReader reader = new(new byte[] { 0x05 }); + this.Serializer.Deserialize(ref reader, ScaledShape, context); + }); + } + + [Test] + public async Task CancellationTokenComesFromContext_Async() + { + CancellationTokenSource cts = new(); + cts.Cancel(); + SerializationContext context = this.CreateContext(multiplier: 1) with { CancellationToken = cts.Token }; + + Pipe pipe = new(); + await Assert.ThrowsAnyAsync(async () => await this.Serializer.SerializeAsync(pipe.Writer, new Scaled(5), ScaledShape, context)); + await Assert.ThrowsAnyAsync(async () => await this.Serializer.DeserializeAsync(pipe.Reader, ScaledShape, context)); + } + + [Test] + public void MaxDepthComesFromContext() + { + Outer value = new(new Inner(3)); + + // The serializer's own StartingContext permits this depth. + this.Roundtrip(value, OuterShape); + + SerializationContext shallow = this.Serializer.StartingContext with { MaxDepth = 1 }; + Sequence sequence = new(); + Assert.Throws(() => + { + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, value, OuterShape, shallow); + }); + } + + [Test] + public void InitializedContextIsRejected() + { + SerializationContext captured = this.CaptureInFlightContext(); + + ArgumentException ex = Assert.Throws(() => + { + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, captured); + }); + Assert.Equal("startingContext", ex.ParamName); + this.Logger.LogInformation(ex.Message); + + Assert.Throws(() => + { + MessagePackReader reader = new(new byte[] { 0x05 }); + this.Serializer.DeserializeObject(ref reader, ScaledShape, captured); + }); + + // Async overloads reject the context synchronously. + Pipe pipe = new(); + Assert.Throws(() => this.Serializer.SerializeAsync(pipe.Writer, new Scaled(5), ScaledShape, captured)); + Assert.Throws(() => this.Serializer.DeserializeObjectAsync(pipe.Reader, ScaledShape, captured)); + } + + [Test] + public void StartingContextWithCapturedContextIsStillAccepted() + { + // Preserve prior behavior: an in-flight context assigned to StartingContext was never validated. + SerializationContext captured = this.CaptureInFlightContext(); + this.Serializer = this.Serializer with { StartingContext = captured }; + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, this.TimeoutToken); + writer.Flush(); + AssertEncodedInt(sequence, 5); + } + + [Test] + public void ProtectedCreateSerializationContext() + { + DerivedSerializer serializer = new(); + Assert.Equal(6, serializer.GetMultiplierFromCreatedContext(this.CreateContext(multiplier: 6))); + Assert.Throws(() => serializer.GetMultiplierFromCreatedContext(this.CaptureInFlightContext())); + } + + private static void AssertEncodedInt(ReadOnlySequence msgpack, int expected) + { + MessagePackReader reader = new(msgpack); + Assert.Equal(expected, reader.ReadInt32()); + } + + private SerializationContext CreateContext(int multiplier) + { + SerializationContext context = this.Serializer.StartingContext with { CancellationToken = this.TimeoutToken }; + context[MultiplierKey] = multiplier; + return context; + } + + private SerializationContext CaptureInFlightContext() + { + ContextCapture capture = new(); + SerializationContext context = this.CreateContext(multiplier: 1); + context[typeof(ContextCapture)] = capture; + + Sequence sequence = new(); + MessagePackWriter writer = new(sequence); + this.Serializer.Serialize(ref writer, new Scaled(5), ScaledShape, context); + return capture.Context ?? throw new InvalidOperationException("The converter did not capture its context."); + } + + [MessagePackConverter(typeof(ScaledConverter))] + internal partial record struct Scaled(int Value); + + [GenerateShapeFor] + [GenerateShapeFor] + internal partial class Witness; + + internal partial record Outer(Inner? Inner); + + internal partial record Inner(int Value); + + internal class ContextCapture + { + internal SerializationContext? Context { get; set; } + } + + internal class ScaledConverter : MessagePackConverter + { + public override Scaled Read(ref MessagePackReader reader, SerializationContext context) + => new(reader.ReadInt32() / GetMultiplier(context)); + + public override void Write(ref MessagePackWriter writer, in Scaled value, SerializationContext context) + { + if (context[typeof(ContextCapture)] is ContextCapture capture) + { + capture.Context = context; + } + + writer.Write(value.Value * GetMultiplier(context)); + } + + private static int GetMultiplier(SerializationContext context) => context[MultiplierKey] is int multiplier ? multiplier : 1; + } + + private record DerivedSerializer : MessagePackSerializer + { + internal int GetMultiplierFromCreatedContext(SerializationContext startingContext) + { + using DisposableSerializationContext context = this.CreateSerializationContext(Witness.GeneratedTypeShapeProvider, startingContext); + Assert.NotNull(context.Value.TypeShapeProvider); + return (int)context.Value[MultiplierKey]!; + } + } +} From 8d0e5ee8ebed46cd033b2f823c58640a801f1937 Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Mon, 28 Sep 2026 18:17:29 -0600 Subject: [PATCH 2/3] Clarify initialized serialization context restrictions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docfx/docs/custom-converters.md | 2 +- src/Nerdbank.MessagePack/MessagePackSerializer.cs | 2 +- src/Nerdbank.MessagePack/SerializationContext.cs | 7 +++---- .../PerCallSerializationContextTests.cs | 2 +- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/docfx/docs/custom-converters.md b/docfx/docs/custom-converters.md index 14027a28..76652f7e 100644 --- a/docfx/docs/custom-converters.md +++ b/docfx/docs/custom-converters.md @@ -186,7 +186,7 @@ Modify state on an existing @Nerdbank.MessagePack.MessagePackSerializer by captu #### Per-call state -When the state varies from one call to the next (e.g. per RPC message rather than per connection), creating a new @Nerdbank.MessagePack.MessagePackSerializer for each call is unnecessary. +When the state varies from one call to the next (e.g. per RPC message rather than per connection), creating a new for each call is unnecessary. Instead, pass a directly to one of the overloads that accepts one, such as . These overloads use the supplied context instead of , and take their cancellation token from its property. The context is typically derived from so that it retains any other settings on it: diff --git a/src/Nerdbank.MessagePack/MessagePackSerializer.cs b/src/Nerdbank.MessagePack/MessagePackSerializer.cs index 881b3052..4f374e6b 100644 --- a/src/Nerdbank.MessagePack/MessagePackSerializer.cs +++ b/src/Nerdbank.MessagePack/MessagePackSerializer.cs @@ -236,7 +236,7 @@ public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeSh /// Its is used to cancel the operation. /// This is typically derived from using a expression. /// - /// Thrown if belongs to a serialization operation that is already in progress, such as the context given to a converter. + /// Thrown if has already been initialized for a serialization operation and cannot be used as a starting context. [OverloadResolutionPriority(-1)] // prefer the CancellationToken overload when the caller passes `default`. public void SerializeObject(ref MessagePackWriter writer, object? value, ITypeShape shape, SerializationContext startingContext) { diff --git a/src/Nerdbank.MessagePack/SerializationContext.cs b/src/Nerdbank.MessagePack/SerializationContext.cs index 2e9a2f61..4104d36c 100644 --- a/src/Nerdbank.MessagePack/SerializationContext.cs +++ b/src/Nerdbank.MessagePack/SerializationContext.cs @@ -359,9 +359,8 @@ internal void Initialize(MessagePackSerializer owner, ConverterCache cache, ITyp /// The name of the parameter that supplied this context. /// Thrown if this context has already been initialized for a serialization operation. /// - /// A context that a converter receives has been initialized for an in-progress operation. - /// Passing such a context to a top-level serializer method would start a new operation that - /// shares nothing with the original one (e.g. reference preservation), which is almost certainly a bug. + /// A context that a converter receives has already been initialized and cannot be used to start another operation. + /// Converters should use to (de)serialize nested values, passing along the context they received. /// internal readonly void ThrowIfInitialized(string paramName) { @@ -372,7 +371,7 @@ internal readonly void ThrowIfInitialized(string paramName) [DoesNotReturn] static void Throw(string paramName) => throw new ArgumentException( - "This context belongs to a serialization operation that is already in progress. Custom converters should never call top-level serializer methods. Instead, use the converter returned by SerializationContext.GetConverter to (de)serialize nested values, passing along the context it was given.", + "This context has already been initialized for a serialization operation and cannot be used as a starting context. Custom converters should use SerializationContext.GetConverter to (de)serialize nested values, passing along the context they were given.", paramName); } diff --git a/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs index f2a76de9..35c4bba7 100644 --- a/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs +++ b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs @@ -201,7 +201,7 @@ public void InitializedContextIsRejected() [Test] public void StartingContextWithCapturedContextIsStillAccepted() { - // Preserve prior behavior: an in-flight context assigned to StartingContext was never validated. + // Preserve prior behavior: an already-initialized context assigned to StartingContext was never validated. SerializationContext captured = this.CaptureInFlightContext(); this.Serializer = this.Serializer with { StartingContext = captured }; From 1fffefcd6df9db32dde90e683e18416804284c5a Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Mon, 28 Sep 2026 18:36:44 -0600 Subject: [PATCH 3/3] Use generated shapes in per-call context tests Avoid reflection-based type shape resolution in the new tests so they work under NativeAOT, including the Linux CI test executable. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../PerCallSerializationContextTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs index 35c4bba7..450bca7f 100644 --- a/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs +++ b/test/Nerdbank.MessagePack.TUnit/PerCallSerializationContextTests.cs @@ -8,8 +8,8 @@ public partial class PerCallSerializationContextTests : MessagePackSerializerTes { private const string MultiplierKey = "PerCallSerializationContextTests.Multiplier"; - private static readonly ITypeShape ScaledShape = TypeShapeResolver.ResolveDynamicOrThrow(); - private static readonly ITypeShape OuterShape = TypeShapeResolver.ResolveDynamicOrThrow(); + private static readonly ITypeShape ScaledShape = Witness.GeneratedTypeShapeProvider.GetTypeShapeOrThrow(); + private static readonly ITypeShape OuterShape = Witness.GeneratedTypeShapeProvider.GetTypeShapeOrThrow(); [Test] public void Serialize_Deserialize_Generic()