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
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