Tobias Koller
Tobias Koller

Reputation: 2186

c# JsonConverter Attribute with DependencyInjection

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?

Upvotes: 1

Views: 4447

Answers (1)

Axel Zarate
Axel Zarate

Reputation: 576

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.

Upvotes: 2

Related Questions