Search code examples
c#asp.net-mvcjson.netautofacasp.net-core-3.1

Replace MvcNewtonsoftJsonOptions for every request received


Is there any way to replace MvcNewtonsoftJsonOptions for every request?

How I register the MvcNewtonsoftJsonOptions :

private static void AddJsonFormatterServices(IServiceCollection services) {
   services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());            
}
// This needs to replaced somehow for every request.

In OurMvcJsonOptions I register the JSonConverters. This service reads all the json Convertors and add it in the JSONSerializer settings Convertors.

Problem: The issue here is that one of the convertor is using an Interface resolved from DI Per Request and as it is now the global scope it will resolve the component from the global scope. Now when a request is received it still use the component from the global context which do not contain information required.

I have already tried the IResourceFilter and IContractResolver. I think the issue is similar to one that is mentioned here but I couldn't figured it out using the solutions mentioned there.

There is also a similar question here but that has not solved my problem as the formatters in the latest version has been removed.

To summarize the problem, the MVC register the MvcNewtonsoftJsonOptions as a singleton while I need it to be created for every request so that I have the correct JsonConverter for the values in the request.


Solution

  • If you have an type that is solved through Dependency Injection, but have a resource that require a different configuration or different scoping of the DI registration. The easiest way is to do second registration to the DI with the different implementation and/or scoping.

    So if you already have:

    private static void AddJsonFormatterServices(IServiceCollection services) {
       services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());            
    }
    

    You can add the specialized:

        private static void AddJsonFormatterServices(IServiceCollection services) {
    
     services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());            
    
        services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<OurSpecializedMvcJsonOptions>, OurSpecializedMvcJsonOptions>());            
        }