From b325aeb4cce5a9ff0b663c67ccabb3bd5d04cb34 Mon Sep 17 00:00:00 2001 From: Andrew Watson Date: Tue, 31 Aug 2021 10:26:42 +1000 Subject: [PATCH] Fix MessageSerializer to create a new JsonSerializer per operation. --- .../Transport/Protocol/MessageSerializer.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/source/Halibut/Transport/Protocol/MessageSerializer.cs b/source/Halibut/Transport/Protocol/MessageSerializer.cs index 6dd8dbe9..427b0df0 100644 --- a/source/Halibut/Transport/Protocol/MessageSerializer.cs +++ b/source/Halibut/Transport/Protocol/MessageSerializer.cs @@ -10,18 +10,15 @@ namespace Halibut.Transport.Protocol { public class MessageSerializer : IMessageSerializer { - readonly JsonSerializer serializer; - readonly RegisteredSerializationBinder binder = new RegisteredSerializationBinder(); readonly HashSet messageContractTypes = new HashSet(); - public MessageSerializer() - { - serializer = CreateDefaultSerializer(); - } - - JsonSerializer CreateDefaultSerializer() + // NOTE: Do not share the serializer between Read/Write, the HalibutContractResolver adds OnSerializedCallbacks which are specific to the + // operation that is in-progress (and if the list is being enumerated at the time causes an exception). And probably adds a duplicate each time the + // type is detected. It also makes use of a static, StreamCapture.Current - which seems like a badâ„¢ idea, perhaps this can be straightened out? + // For now, just ensuring each operation does not interfere with each other. + JsonSerializer CreateSerializer() { var jsonSerializer = JsonSerializer.Create(); jsonSerializer.Formatting = Formatting.None; @@ -50,7 +47,7 @@ public void WriteMessage(Stream stream, T message) // for the moment this MUST be object so that the $type property is included // If it is not, then an old receiver (eg, old tentacle) will not be able to understand messages from a new sender (server) // Once ALL sources and targets are deserializing to MessageEnvelope, (ReadBsonMessage) then this can be changed to T - serializer.Serialize(bson, new MessageEnvelope { Message = message }); + CreateSerializer().Serialize(bson, new MessageEnvelope { Message = message }); } } @@ -59,7 +56,7 @@ public T ReadMessage(Stream stream) using (var zip = new DeflateStream(stream, CompressionMode.Decompress, true)) using (var bson = new BsonDataReader(zip) { CloseInput = false }) { - var messageEnvelope = serializer.Deserialize>(bson); + var messageEnvelope = CreateSerializer().Deserialize>(bson); if (messageEnvelope == null) throw new Exception("messageEnvelope is null");