c# - How can Json.NET perform dependency injection during deserialization? -


When I do not have a default constructor, or you can use dependency injection to pass its dependence < Code> Newtonsoft.Json to create such an object?

For example:

  public class SomeFoo {private readonly IFooDependency _ dependency; Public SomeFoo (IFooDependency Dependency) {If (Dependency == blank) Throw New ArgumentNullException ("Dependency"); _ Dependency = dependency; } Public string data {get; Set; } Public int MoreData {get; Set; } Public Zero DoFoo () {Data = _ dependency. GetFooData (); MoreData = _dependency.GetMoreFooDate (); }}  

During serialization, I only care about storing data and Mordata (and object type), but do not mess things up for the moment. Now, to deserialize, do I

  var obj = JsonConvert.Deserialize object < SomeFoo & gt; (Jsontext);  

How do I tell Jason Convert about my Di container?

(Note: around one thing will always default constructor in my classes, and call any of the service locator to the required dependencies. I with constructors such

I have concerns posted by Steven I agree differently and Mark Seaman posted However, if you still want to go this way, then

>

  internal square Ninja Converter converter & lt; T & gt;: custom Revolution converter & lt; T & gt; where T: class {private Reedonli Aiarjeslrut _ Ssewa Loketr; public NinjectCustomConverter (IResolutionRoot serviceLocator) {_serviceLocator = serviceLocator;} public override Create T (type object type) {return _serviceLocator.Get (objectType) as T;}}  

Then make sure that you have your DI container Also provide the converter through the retrieve. The following code must be deferred to your object by and DE:

  var ninjectConverter = kernel.Get & lt; NinjectCustomConverter & lt; Serialized object & gt; & Gt; (); Var Settings = New JsonSerializer Settings (); Settings.Converters.Add (ninjectConverter); Var example = JsonConvert.DeserializeObject & lt; SerializedObject & gt; (Jason, settings);  

.


Comments