为收到的每个请求替换 MvcNewtonsoftJsonOptions
Replace MvcNewtonsoftJsonOptions for every request received
有没有办法为每个请求替换 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。
我认为这个问题与提到的问题相似 here 但我无法使用那里提到的解决方案解决它。
也有类似的问题,但这并没有解决我的问题,因为最新版本中的格式化程序已被删除。
总而言之,MVC 将 MvcNewtonsoftJsonOptions 注册为单例,而我需要为每个请求创建它,以便我对请求中的值拥有正确的 JsonConverter。
如果您有一个通过依赖注入解决的类型,但有一个资源需要不同的配置或不同的 DI 注册范围。最简单的方法是使用不同的实现 and/or 范围对 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>());
}
有没有办法为每个请求替换 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。 我认为这个问题与提到的问题相似 here 但我无法使用那里提到的解决方案解决它。
也有类似的问题
总而言之,MVC 将 MvcNewtonsoftJsonOptions 注册为单例,而我需要为每个请求创建它,以便我对请求中的值拥有正确的 JsonConverter。
如果您有一个通过依赖注入解决的类型,但有一个资源需要不同的配置或不同的 DI 注册范围。最简单的方法是使用不同的实现 and/or 范围对 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>());
}