我正在使用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设置为构造函数参数?
我知道这是一个老问题,但我认为this是你正在寻找的解决方案。
总之,您必须将JsonSerializerSettings.ContractResolver
设置为您自己的DefaultContractResolver
类的实现,您可以在其中覆盖CreateObjectContract
方法。使用此方法可以使用依赖项注入容器来创建自定义转换器的实例。