When I have a class with no default constructor, i.e. using dependency injection to pass its dependencies, can Newtonsoft.Json
create such an object?
I agree with the separation of concerns posted by Steven, and the answer Mark Seemann has posted here. However, if you still want to go this way, here is a solution that may help:
Inherit a CustomCreationConverter
:
internal class NinjectCustomConverter : CustomCreationConverter where T : class
{
private readonly IResolutionRoot _serviceLocator;
public NinjectCustomConverter(IResolutionRoot serviceLocator)
{
_serviceLocator = serviceLocator;
}
public override T Create(Type objectType)
{
return _serviceLocator.Get(objectType) as T;
}
}
Then make sure you retrieve this converter instance via your DI container as well. The code below will deserialize and perform DI on your object:
var ninjectConverter = kernel.Get>();
var settings = new JsonSerializerSettings();
settings.Converters.Add(ninjectConverter);
var instance = JsonConvert.DeserializeObject(json, settings);
Here is a complete working example.