Friday, January 24, 2025

.NET: How to Configure JsonSerializerOptions Correctly in a Builder ServiceCollection

Recently saw an issue in one of our applications that Configures JsonSerializerOptions as part of the builders ServiceCollection (FunctionsApplicationBuilderWebApplicationBuilder etc). 

To give a minimal example, say we want to configure JsonSerializerOptions.WriteIndented to true (in configuration it's false by default).
FunctionsApplicationBuilder builder = FunctionsApplication.CreateBuilder(args);

builder.Services.Configure<JsonSerializerOptions>(options =>
{
    options = new JsonSerializerOptions
    {
        WriteIndented = true,
    };
});
Above seems correct and could be easily unnoticeable in reviewing a PR.

But above is actually incorrect. If you resolve the JsonSerializerOptions and inspect the value of WriteIndented, it would still be false.
JsonSerializerOptions configuredJsonSerializerOptions = builder.Services.BuildServiceProvider().GetService<IOptions<JsonSerializerOptions>>().Value;

// This will be false.
bool isWriteIndented = configuredJsonSerializerOptions.WriteIndented;
The correct way is,
builder.Services.Configure<JsonSerializerOptions>(options =>
{
    options.WriteIndented = true;
});
That is rather than initializing a new JsonSerializerOptions with required configurations, update the existing JsonSerializerOptions that was supplied in the delegate.

Now JsonSerializerOptions will have the correct value.
JsonSerializerOptions configuredJsonSerializerOptions = builder.Services.BuildServiceProvider().GetService<IOptions<JsonSerializerOptions>>().Value;

// This will be true.
bool isWriteIndented = configuredJsonSerializerOptions.WriteIndented;
This is a simple mistake that could potentially cause a lot of issues, so hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment