【发布时间】:2019-03-06 00:27:10
【问题描述】:
我正在使用 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})]
但是我会得到一个 NullReference-Exception。
有没有办法将 null 设置为构造函数参数?
【问题讨论】:
-
谢谢,但在我的情况下,我需要在无法使用“new”的属性中传递这个“可为空”。
-
你不应该对属性使用依赖注入,因为属性没有行为,因此没有什么可以注入的。您需要做的是将依赖项注入到具有行为的服务中。请参阅 this example 在 MVC 中使用过滤器。另请阅读passive attributes。
-
@NightOwl888 在对它如此挑剔之前,请多了解一下这个问题。我承认这个问题可能更清楚,但无论哪种方式,问题都是一样的。该属性不需要 DI,已解析的转换器类型需要。例如
[JsonConverter(typeof(MyConverter))]解析转换器的属性需要DI。JsonConverterAttribute本身可能没有,但是由 newtonsoft 创建的MyConverter可以。如果 OP 可以新建自己的InterfaceJsonConverter,这将不是问题。实例化不受 OP 控制,这意味着 DI 不受他的控制。
标签: c# dependency-injection json.net