using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
public static void Main()
var builder = new ContainerBuilder();
builder.RegisterType<QueryObjectCreator>()
.As<ICustomObjectCreator<IQuery>>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(CustomConverter<>)).AsSelf().InstancePerLifetimeScope();
var container = builder.Build();
Func<JsonSerializerSettings> settingsFactory = () =>
var settings = new JsonSerializerSettings();
settings.ContractResolver = new AutofacContractResolver(container);
JsonConvert.DefaultSettings = settingsFactory;
var myObject = new MyObject { Query = new Query(42) };
var json = JsonConvert.SerializeObject(myObject);
myObject = JsonConvert.DeserializeObject<MyObject>(json);
Console.WriteLine(myObject.Query.MyProperty);
public class AutofacContractResolver : DefaultContractResolver
private readonly IContainer _container;
public AutofacContractResolver(IContainer container)
protected override JsonConverter ResolveContractConverter(Type objectType)
var customObjectCreatorType = typeof(ICustomObjectCreator<>).MakeGenericType(objectType);
if (!_container.IsRegistered(customObjectCreatorType))
return base.ResolveContractConverter(objectType);
var customConverterType = typeof(CustomConverter<>).MakeGenericType(objectType);
return (JsonConverter) _container.Resolve(customConverterType);
public class CustomConverter<T> : JsonConverter
public ICustomObjectCreator<T> ObjectCreator { get; set; }
public CustomConverter() { }
public CustomConverter(ICustomObjectCreator<T> objectCreator)
Console.WriteLine("Constructor called");
ObjectCreator = objectCreator;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var jObject = JObject.Load(reader);
var target = Create(objectType, jObject);
serializer.Populate(jObject.CreateReader(), target);
protected T Create(Type objectType, JObject jObject)
var type = jObject.GetValue("type", StringComparison.OrdinalIgnoreCase);
return ObjectCreator.Create(type != null ? type.Value<string>() : null);
public override bool CanConvert(Type type)
return type == typeof(T);
public override void WriteJson(JsonWriter jsonWriter, object o, JsonSerializer serializer)
public interface ICustomObjectCreator<out T>
public class QueryObjectCreator : ICustomObjectCreator<IQuery>
public IQuery Create(string type)
Console.WriteLine("Create called");
var concreteObject = new Query();
return (IQuery)concreteObject;
int MyProperty { get; set; }
public class Query : IQuery
public int MyProperty { get; set; }
public Query(int myProperty)
public IQuery Query { get; set; }