Click or drag to resize
Json.NETDeserialize with dependency injection
 

This sample deserializes JSON using dependency injection.

Sample
Types
 1public class AutofacContractResolver : DefaultContractResolver
 2{
 3    private readonly IContainer _container;
 4
 5    public AutofacContractResolver(IContainer container)
 6    {
 7        _container = container;
 8    }
 9
10    protected override JsonObjectContract CreateObjectContract(Type objectType)
11    {
12        // use Autofac to create types that have been registered with it
13        if (_container.IsRegistered(objectType))
14        {
15            JsonObjectContract contract = ResolveContact(objectType);
16            contract.DefaultCreator = () => _container.Resolve(objectType);
17
18            return contract;
19        }
20
21        return base.CreateObjectContract(objectType);
22    }
23
24    private JsonObjectContract ResolveContact(Type objectType)
25    {
26        // attempt to create the contact from the resolved type
27        IComponentRegistration registration;
28        if (_container.ComponentRegistry.TryGetRegistration(new TypedService(objectType), out registration))
29        {
30            Type viewType = (registration.Activator as ReflectionActivator)?.LimitType;
31            if (viewType != null)
32            {
33                return base.CreateObjectContract(viewType);
34            }
35        }
36
37        // fall back to using the registered type
38        return base.CreateObjectContract(objectType);
39    }
40}
41
42public class TaskController
43{
44    private readonly ITaskRepository _repository;
45    private readonly ILogger _logger;
46
47    public TaskController(ITaskRepository repository, ILogger logger)
48    {
49        _repository = repository;
50        _logger = logger;
51    }
52
53    public ITaskRepository Repository
54    {
55        get { return _repository; }
56    }
57
58    public ILogger Logger
59    {
60        get { return _logger; }
61    }
62}
Usage
 1ContainerBuilder builder = new ContainerBuilder();
 2builder.RegisterType<TaskRepository>().As<ITaskRepository>();
 3builder.RegisterType<TaskController>();
 4builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>();
 5
 6IContainer container = builder.Build();
 7
 8AutofacContractResolver contractResolver = new AutofacContractResolver(container);
 9
10string json = @"{
11  'Logger': {
12    'Level':'Debug'
13  }
14}";
15
16// ITaskRespository and ILogger constructor parameters are injected by Autofac 
17TaskController controller = JsonConvert.DeserializeObject<TaskController>(json, new JsonSerializerSettings
18{
19    ContractResolver = contractResolver
20});
21
22Console.WriteLine(controller.Repository.GetType().Name);
23// TaskRepository