How can Json.NET perform dependency injection during deserialization?

前端 未结 3 2046
悲哀的现实
悲哀的现实 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:19

    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.

提交回复
热议问题