Deserialize with dependency injection |
This sample deserializes JSON using dependency injection.
public class AutofacContractResolver : DefaultContractResolver { private readonly IContainer _container; public AutofacContractResolver(IContainer container) { _container = container; } protected override JsonObjectContract CreateObjectContract(Type objectType) { // use Autofac to create types that have been registered with it if (_container.IsRegistered(objectType)) { JsonObjectContract contract = ResolveContact(objectType); contract.DefaultCreator = () => _container.Resolve(objectType); return contract; } return base.CreateObjectContract(objectType); } private JsonObjectContract ResolveContact(Type objectType) { // attempt to create the contact from the resolved type IComponentRegistration registration; if (_container.ComponentRegistry.TryGetRegistration(new TypedService(objectType), out registration)) { Type viewType = (registration.Activator as ReflectionActivator)?.LimitType; if (viewType != null) { return base.CreateObjectContract(viewType); } } // fall back to using the registered type return base.CreateObjectContract(objectType); } } 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; } } }
ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<TaskRepository>().As<ITaskRepository>(); builder.RegisterType<TaskController>(); builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>(); 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<TaskController>(json, new JsonSerializerSettings { ContractResolver = contractResolver }); Console.WriteLine(controller.Repository.GetType().Name); // TaskRepository