Is there a way to get dependency injection using a custom JsonConverter converter

Not exactly the same:

How do I nest dependencies using Ninject where instances are deserialized from json

If the answer is that your data class that you deserialized does not need a service anyway. Is there a way to use dependency injection with a class derived from JsonConverter ? For example, if you have this:

 [JsonConverter(typeof(MyCustomConverter))] public class Foo { public string SomeProp { get; set; } } 

and

 public class MyCustomConverter : JsonConverter { private readonly IMyService myService; public MyCustomConverter(IMyService _myService) { myService = _myService; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var bar = myService.SomeFunctionThatMightEffectDeserialization(); //... } } 

Is it even possible to connect to the way JSON.Net creates an instance of MyCustomConverter to force Ninject to do this?

EDIT . This does NOT introduce the service into Foo , as a suggested hoax. This is only entered in MyCustomConverter to then deserialize Foo .

+6
source share
1 answer

It's a bit of a hack, but you can do something similar by setting ContractResolver in the JsonSerializerSettings settings. In this case, using Autofac:

 var builder = new ContainerBuilder(); builder.RegisterInstance(myService); var container = builder.Build(); var settings = new JsonSerializerSettings { ContractResolver = new AutofacContractResolver(container), }; 

and then in the converter:

 var jsonContract = serializer.ContractResolver.ResolveContract(typeof(IMyService)); var service = (IMyService)jsonContract.DefaultCreator(); 

Thus, you really do not enter the service into the converter, but at least you can access it without a specific dependency. In addition, you do not use the same Autofac container as your application, but create a new one. Not perfect, but it's something :)

+1
source

All Articles