【发布时间】:2014-02-18 16:33:52
【问题描述】:
当我有一个没有默认构造函数的类,即使用依赖注入来传递它的依赖关系时,Newtonsoft.Json 可以创建这样的对象吗?
例如:
public class SomeFoo
{
private readonly IFooDependency _dependency;
public SomeFoo(IFooDependency dependency){
if(dependency == null)
throw new ArgumentNullException("dependency");
_dependency = dependency;
}
public string Data { get; set; }
public int MoreData { get; set; }
public void DoFoo(){
Data = _dependency.GetFooData();
MoreData = _dependency.GetMoreFooDate();
}
}
在序列化过程中,我只关心存储 Data 和 MoreData(以及对象的类型,但暂时不要让事情复杂化)。现在,要反序列化,我可以调用类似
var obj = JsonConvert.DeserializeObject<SomeFoo>(jsonText);
如何让 JsonConvert 知道我的 DI 容器?
(注意:解决方法是在我的类中始终使用默认构造函数,并在其中调用 Service Locator 以获取我需要的任何依赖项。我只是在寻找一些更干净的解决方案,而不用这样污染我的类构造函数)。
【问题讨论】:
-
DI and JSON.NET 的可能重复项
标签: c# json dependency-injection json.net ninject