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?
You shouldn't let JsonConvert
know anything about your DI container. The problems you're experiencing are caused by a flaw in the design of your application. The flaw here is that you mix data and behavior.
If you separate the data from the behavior your problem (and many other problems) will simply go away. You can do this by creating two classes: one for the data, and one for the behavior:
public class SomeFoo
{
public string Data { get; set; }
public int MoreData { get; set; }
}
public class SomeFooHandler
{
private readonly IFooDependency _dependency;
public SomeFooHandler(IFooDependency dependency) {
_dependency = dependency;
}
public void Handle(SomeFoo foo) {
foo.Data = _dependency.GetFooData();
foo.MoreData = _dependency.GetMoreFooDate();
}
}
Since now data and behavior are separated, SomeFoo
can be serialized without any problem and SomeFooHandler
can simply be injected. SomeFoo
has becomes a Parameter Object.