c#JsonConverter属性与DependencyInjection

问题描述 投票:0回答:1

我正在使用JsonConverter来解析asp核心中的接口。

这是我的JsonConverter-Impl。

 public class InterfaceJsonConverter<T> : Newtonsoft.Json.JsonConverter
    {
        public InterfaceJsonConverter(Type[] types, ITypeRepository typeRepository=null){
            ...
        }
    }

这就是我所说的

[JsonConverter(typeof(InterfaceJsonConverter<ISomeInterface>), new object[] {new Type[]{
        typeof(MyCustomType)
    }})]
    public interface ISomeInterface{
    ...
    }

基本上,当我删除可选参数“typeRepository”时,这种方法很有效。但我需要这个参数由dependencyInjection设置。

我怎么设置这个?我已经尝试在interface-Attribute中将此参数设置为null

[JsonConverter(typeof(InterfaceJsonConverter<ISomeInterface>), new object[] {new Type[]{
        typeof(MyCustomType)
    },null})]

但后来我会得到一个Null Reference-Exception。

有没有办法将null设置为构造函数参数?

c# dependency-injection json.net
1个回答
0
投票

我知道这是一个老问题,但我认为this是你正在寻找的解决方案。

总之,您必须将JsonSerializerSettings.ContractResolver设置为您自己的DefaultContractResolver类的实现,您可以在其中覆盖CreateObjectContract方法。使用此方法可以使用依赖项注入容器来创建自定义转换器的实例。

© www.soinside.com 2019 - 2024. All rights reserved.