具有Dependecy的自定义Json Converter [英] Custom Json Converter with dependecy
问题描述
出于某种原因,我必须在ASP.NET Core中使用自定义的JsonConverter
,并且我需要在JsonInputFormatter
中使用它.我发现的唯一方法是使用AddJsonOption
扩展方法,如下所示:
I have to use a custom JsonConverter
with ASP.NET Core for a reason, and I need to use it with JsonInputFormatter
. The only way I've found is to use AddJsonOption
extension method like this:
services
.AddMvc()
.AddJsonOptions(jso => jso.SerializerSettings.Converters.Add(new CustomConverter()))
但是它有一个缺陷:CustomConverter
需要来自DI容器的依赖关系,而这在配置时无法轻易解决.
所以问题来了:是否有任何程序员友好的方式来提供依赖于ASP.NET Core JsonInputFormatter
的JsonConverter
?
But it has a flaw: CustomConverter
requires a dependency from a DI container which cannot be easily solved at configuration time.
So the question: is there any programmer friendly way to supply a JsonConverter
with dependency to ASP.NET Core JsonInputFormatter
?
推荐答案
一种快速的解决方法是将其推迟到Configure
方法.
One quick workaround would be to postpone it to the Configure
method.
public Confiugre(IAppBuilder app, IOptions<MvcOptions> mvcOptions, IOptions<MvcJsonOptions> jsonOptions)
{
var formatter = mvcOptions.InputFormatters.OfType<JsonInputFormatter>().Single();
jsonOptions.SerializerSettings.Converters.Add(
new CustomConverter(formatter));
...
}
虽然还是有点脏;)
这篇关于具有Dependecy的自定义Json Converter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!