InvalidOperationException: A 'JsonSerializerOptions' instance associated with a 'JsonSerializerContext' instance cannot be mutated once the context has been instantiated.
Y esterday I introduced the System.Text.Json source generator and showed you how to use it in ASP.NET Core. What I didn’t told you that it didn’t go so smoothly.
In the post yesterday I showed the AddJsonOptions()
on the IServiceCollection
to specify our JsonContext
class on the JsonSerializerOptions.
However this was not my first attempt. The original code I wrote looked like this:
This resulted in a runtime exception:
An error occurred while starting the application.
InvalidOperationException: A 'JsonSerializerOptions' instance associated with a 'JsonSerializerContext' instance cannot be mutated once the context has been instantiated.
System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext context)
Did you notice the difference between the 2 code samples? In the first example, I added the custom Json Converter BEFORE the source generator context. In the second example, I added the Json converter AFTER the context.
Once we have added the source generator context, we can no longer mutate the JsonSerializer. So the lesson learned is ‘always set the JsonContext last’.