-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Background and Motivation
We have a set of contract libraries that we create, all of which depend on a "core" contract library, which defines the json serialization options as a static property. Currently, this property is internal, and we use InternalsVisibleTo to give access to this property to the actual contracts projects, but it would be preferable to just have this be a public property.
The reason we don't just have it as public is that we don't want consumers of our contracts to modify it (as it's a shared static instance). However, reading through the source of JsonSerializerOptions I noticed that it contains a VerifyMutable method, meaning that there are cases where a JsonSerializerOptions is not mutable. I suggest enabling a simple public API that can take a given JsonSerializerOptions and "lock" it, or "make it immutable", so that it's safe to share in library code. This would be a no-op if the options is already immutable.
I do not know what name would be best for such a method, so the one below is just a suggestion.
Proposed API
namespace System.Text.Json
{
public partial class JsonSerializerOptions
{
+ public bool IsImmutable { get; }
+ public void EnsureImmutable();
}Usage Examples
var options = new JsonSerializerOptions { TypeInfoResolver = new MyFancyResolver(), WriteIndented = true };
Console.WriteLine(options.IsLocked); // False
var converter = options.GetConverter(typeof(MyPoco)); // Returns an uncached converter instance
options.Lock(); // lock the instance and initialize the metadata cache
Console.WriteLine(options.IsLocked); // True
converter = options.GetConverter(typeof(MyPoco)); // Returns a cached converter instanceAlternative Designs
We might want to consider exposing equivalent functionality to JsonTypeInfo and JsonPropertyInfo, whose design uses a similar locking design. We're also not certain about naming, the obvious alternative being IsLocked/Lock() but there are concerns that this connotes with exclusive locking.
Risks
I don't see any risk with this API. It would also help codify the fact that a JsonSerializerOptions can be "locked" (today it just happens implicitly).