具有Dependecy的自定义Json Converter [英] Custom Json Converter with dependecy

查看:44
本文介绍了具有Dependecy的自定义Json Converter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我必须在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 JsonInputFormatterJsonConverter?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆