c# - 为收到的每个请求替换 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。
解决方案
如果您有一个通过依赖注入解决的类型,但有一个资源需要不同的配置或不同的 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>());
}
推荐阅读
- jquery - 如何在没有 webpack 的 es6 中导入 npm 模块?
- php - 使用 PHP 使用 XSL 上传 XML 的最佳方式
- elisp - 更新结构字段
- java - 编码的结果相同,但散列的结果不同
- php - 需要 PHP WordPress 注册表单复选框
- ios - SwiftUI 中的一排 Picker 轮子,为什么拖动滚动区域从屏幕上的 Picker 控件偏移?
- python - 尝试构建 Visual Studio Code python 解决方案时如何修复 setup.py 错误
- java - 发出sonarqube gradle任务不适用于java 11
- php - 如何在 PHP 的类继承中只运行父方法?
- amazon-web-services - AWS IOT 限制中的事务与请求之间的差异