首页 > 解决方案 > 为收到的每个请求替换 MvcNewtonsoftJsonOptions

问题描述

有没有办法为每个请求替换 MvcNewtonsoftJsonOptions ?

我如何注册 MvcNewtonsoftJsonOptions :

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

OurMvcJsonOptions我注册了 JSonConverters。该服务读取所有 json 转换器并将其添加到 JSONSerializer 设置转换器中。

问题: 这里的问题是其中一个转换器正在使用从 DI Per Request 解析的接口,并且由于它现在是全局范围,它将从全局范围解析组件。现在,当收到请求时,它仍然使用全局上下文中不包含所需信息的组件。

我已经尝试过 IResourceFilter 和 IContractResolver。我认为这个问题类似于这里提到的问题,但我无法使用那里提到的解决方案来解决这个问题。

这里也有一个类似的问题,但这并没有解决我的问题,因为最新版本中的格式化程序已被删除。

总结这个问题,MVC 将 MvcNewtonsoftJsonOptions 注册为单例,而我需要为每个请求创建它,以便我为请求中的值拥有正确的 JsonConverter。

标签: c#asp.net-mvcjson.netautofacasp.net-core-3.1

解决方案


如果您有一个通过依赖注入解决的类型,但有一个资源需要不同的配置或不同的 DI 注册范围。最简单的方法是使用不同的实现和/或范围对 DI 进行第二次注册。

因此,如果您已经拥有:

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

您可以添加专门的:

    private static void AddJsonFormatterServices(IServiceCollection services) {

 services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<MvcNewtonsoftJsonOptions>, OurMvcJsonOptions>());            

    services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<OurSpecializedMvcJsonOptions>, OurSpecializedMvcJsonOptions>());            
    }

推荐阅读