Instead of using ModelBinder, use an implementation of MediaTypeFormatter.
You can overrides the method "ReadFromStreamAsync" and change the type to whatever you need.
In the example below, the type is changed by resolving the concrete type using the MVC's DependencyResolver, witch works fine for WebAPI.
public class CustomFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
public CustomFormUrlEncodedMediaTypeFormatter() : base() { }
public override Task ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (type.IsInterface)
type = GetConcreteType(type);
return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (type.IsInterface)
type = GetConcreteType(type);
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
private Type GetConcreteType(Type type)
{
object concrete = System.Web.Mvc.DependencyResolver.Current.GetService(type);
return concrete.GetType();
}
}
If you want to do that with the JsonFormatter, it's a better aproach to create a "CustomCreationConverter" for Json.NET, than they can resolve the depenencies for all child objects that you have in your interface.
public class DomainConverter : CustomCreationConverter
{
public DomainConverter() { }
public override bool CanConvert(Type objectType)
{
return objectType.IsInterface;
}
public override object Create(Type objectType)
{
return System.Web.Mvc.DependencyResolver.Current.GetService(objectType);
}
}