1

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?

Tobias Koller
  • 2,116
  • 4
  • 26
  • 46
  • See [Injecting a nullable dependency via constructor requires unity to register that nullable dependency](http://stackoverflow.com/a/41747222/181087) – NightOwl888 Jan 25 '17 at 09:08
  • thanks but in my case I need to pass this "nullable" in an Attribute where I'm not able to use "new". – Tobias Koller Jan 26 '17 at 06:42
  • You aren't supposed to use dependency injection with attributes because attributes have no *behavior* and thus have nothing to inject. What you need to do is inject the dependency into the service that does have behavior. See [this example](http://stackoverflow.com/a/28365933/181087) of using filters in MVC. Also read [passive attributes](http://blog.ploeh.dk/2014/06/13/passive-attributes/). – NightOwl888 Jan 26 '17 at 07:54
  • 2
    @NightOwl888 Please understand the problem a bit more before being so critical aout it. I admit the question could be clearer, but the problem is the same either way. The attribute doesn't need DI, the resolved converter type does. For instance `[JsonConverter(typeof(MyConverter))]` attributes who's resolved converter needs DI. The `JsonConverterAttribute` itself may not, but `MyConverter`, something that is created by newtonsoft, does. If OP could new up his own `InterfaceJsonConverter` this wouldn't be an issue. Instantiation is out of OPs control, which means DI is out of his control. – Douglas Gaskell Dec 19 '20 at 01:26

1 Answers1

2

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.

Axel Zarate
  • 466
  • 4
  • 14