JsonConverter Attribute : deserialize using custom constructor and Autofac

前端 未结 2 1074
渐次进展
渐次进展 2021-01-22 19:03

Am using a custom JsonConverter to convert my JSON object. This is achieved via the JsonConverter attribute to the IQuery object below

[JsonConverter(typeof(Cust         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 19:22

    Suppose an autofac setting like the following:

    public class AutofacContractResolver : DefaultContractResolver
    {
        private readonly IContainer _container;
    
        public AutofacContractResolver(IContainer container)
        {
            _container = container;
        }
    
        protected override JsonObjectContract CreateObjectContract(Type objectType)
        {
            JsonObjectContract contract = base.CreateObjectContract(objectType);
    
            // use Autofac to create types that have been registered with it
            if (_container.IsRegistered(objectType))
            {
               contract.DefaultCreator = () => _container.Resolve(objectType);
            }  
    
            return contract;
        }
    }
    

    Then, suppose your class is like this:

    public class TaskController
    {
        private readonly ITaskRepository _repository;
        private readonly ILogger _logger;
    
        public TaskController(ITaskRepository repository, ILogger logger)
        {
            _repository = repository;
            _logger = logger;
        }
    
        public ITaskRepository Repository
        {
            get { return _repository; }
        }
    
        public ILogger Logger
        {
            get { return _logger; }
        }
    }
    

    Therefore, the usage of the resolver in deserialization could be like:

    ContainerBuilder builder = new ContainerBuilder();
    builder.RegisterType().As();
    builder.RegisterType();
    builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As();
    
    IContainer container = builder.Build();
    
    AutofacContractResolver contractResolver = new AutofacContractResolver(container);
    
    string json = @"{
          'Logger': {
            'Level':'Debug'
          }
    }";
    
    // ITaskRespository and ILogger constructor parameters are injected by Autofac 
    TaskController controller = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
    {
        ContractResolver = contractResolver
    });
    
    Console.WriteLine(controller.Repository.GetType().Name);
    

    You can see more details in http://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm

提交回复
热议问题