How can Json.NET perform dependency injection during deserialization?

前端 未结 3 2021
悲哀的现实
悲哀的现实 2021-01-07 18:53

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?

3条回答
  •  不知归路
    2021-01-07 19:10

    If your objective is to use the injected dependency to modify the data, then you can create a custom Converter.

    With this, you should be able to inject your dependency. Similar to the code below:

     var settings = new JsonSerializerSettings
                {
                    Converters = { new FooConverter(injectedDependency) }
                };
     return JsonConvert.DeserializeObject(json, settings);
    

    There're many samples of how to create a custom Converters, so you can refer to them.

提交回复
热议问题