c# JsonConverter Attribute with DependencyInjection

雨燕双飞 提交于 2020-01-05 04:58:05

问题


I'm using JsonConverter to resolve Interfaces in asp core.

Here is my JsonConverter-Impl.

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

and this is how I call it

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

Basically this works well when I remove my optional Parameter "typeRepository". But I Need this Parameter set by an dependencyInjection.

how can I set this? I already tried to set this Parameter as null in the interface-Attribute like

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

but then I will get an NullReference-Exception.

Is there a way to set null as a constructor-parameter?


回答1:


I know this is an old question, but I think this is the solution you are looking for.

In summary, you must set the JsonSerializerSettings.ContractResolver to your own implementation of the DefaultContractResolver class, where you override the CreateObjectContract method. This method is where you use your dependency injection container to create an instance of the custom converter.



来源:https://stackoverflow.com/questions/41846426/c-sharp-jsonconverter-attribute-with-dependencyinjection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!