Resolve Json.NET interfaces with dependency injection

If you need to resolve interface types during serialization, you need to implement a contract resolver and provide it to json.net. Here is an example:

public class InterfaceContractResolver : DefaultContractResolver
{
    private readonly IKernel _kernel;

    public InterfaceContractResolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        if (objectType.IsInterface)
        {
            var dummy = _kernel.TryGet(objectType);

            if (dummy != null)
            {
                return base.CreateObjectContract(dummy.GetType());
            }
        }

        return base.CreateObjectContract(objectType);
    }
}

Now when creating your serializer, simply create an instance of the contract resolver

var serializer = new JsonSerializer();

serializer.ContractResolver = new InterfaceContractResolver(kernel);

Submit a Comment

Your email address will not be published. Required fields are marked *

Share This