Not quite the same as this:
How do I Inject Dependencies with Ninject, where instances are deserialised from json
Where the answer is that your data class that you deserialized shouldn't need a service anyway. Is there a way to use dependency inject with a class derived from JsonConverter
? For example, if you had 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 there anyway to hook into how JSON.Net instantiates MyCustomConverter
to get it to let Ninject do it's thing?
EDIT This is NOT injecting a service into Foo
like the suggested dupe. This is injecting only into MyCustomConverter
so that it can then deserialize Foo
.
MyCustomConverter
type that allows anIMyService
to be returned in custom event args. Awkward, but doable. Also, maybe see here: blog.ploeh.dk/2013/09/08/di-and-events-third-party-connect – DowelJsonConverterAttribute
is sealed, so I can't derive. Somewhere in the internal workings of JSON.Net that attribute gets read when it tries to deserialize that class and an instance ofMyCustomConverter
gets created. The key part of the question is whether or not there's a place to hook into that process. – KaenelJsonTypeReflector
is the class responsible for the instantication, if you'd like to have a look. – DennardBindHttpFilter
in ninject, but I'm not sure if it's generally possible. I need the attributeJsonConverter(typeof(MyCustomConverter))
for JSON.Net, but I need json.net to let DI construct the instance ofMyCustomConverter
and that seems to be buried inJsonTypeReflector
which isinternal static
– Kaenel