The Problem
If you’ve been working with .NET long enough, especially with building and consuming RESTful APIs, I’m sure you will have seen code which looks like this scattered around the code base.
public class MyServiceWithOwnOptions
{
private readonly JsonSerializerOptions options = new JsonSerializerOptions()
{
AllowTrailingCommas = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = false
};
// ** snip for brevity **
}
Each usage of the json serializer options gets created in the class it is needed in. This is ok if only used in one place but if you are talking to multiple end points on the same api with the same configuration then there’s potential this code can get duplicated and become out of sync.
A Solution
How can we make it so there is only one default set of serilizer options being used? Yup, you’ve guessed it … use Dependency Injection.
We register strongly typed configuration options to be injected into services, typed cients etc. so why not the serilization settings?
In ConfigureServices
add the registration as you would with any other configuration setting the values as required.
services.AddSingleton<JsonSerializerOptions>(new JsonSerializerOptions()
{
AllowTrailingCommas = true,
});
And then like any other dependency, request it to be passed in through constructor injection using the power of dependency injection.
public class MyServiceOptionsInjected
{
private readonly JsonSerializerOptions _options;
public MyServiceOptionsInjected(JsonSerializerOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
}
When the MyServiceOptionsInjected
gets requested from the DI container the singleton instance of the options will be injected.
Conclusion
In this post we have looked at how to inject JsonSerializerOptions
to keep the common ones defined in one place. This allows for the same options to be used and not duplicated.
Full example code can be found on my github repo.
Any questions/comments then please contact me on Twitter @WestDiscGolf