Yes, but JSONJson.NetNET is not integrated with ASP.NetNET Core Dependency Injectiondependency injection. So the deserializer just does not know how to create an instance of ITestInterface.
Yes, you should put some efforts to cover such a scenario and a custom contract resolver seems the most proper way for this. The steps that you should take are the following:
Define a custom contract resolver. You could base it on
DefaultContractResolverused by JSONJson.NetNET. You should pass instance ofIServiceProviderto this resolver which will be used for instantiation of registered types.In
Startup.ConfigureServices()register all types that could be used by contract resolver during JSONJson.NetNET deserialization.Create instance of custom contract resolver and set it to
SerializerSettings.ContractResolver. InStartup.ConfigureServices()you don't yet have access toIServiceProviderbecause it's not yet created (since services are still registered). However, you could create it by yourself by callingservices.BuildServiceProvider(). But make sure you have registered all required services before this call.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ITestInterface, TestClass>();
// Register all other services here
// ...
services.AddMvc(options => options.RespectBrowserAcceptHeader = true)
.AddXmlDataContractSerializerFormatters()
.AddXmlSerializerFormatters()
.AddJsonOptions(o =>
{
o.SerializerSettings.ContractResolver = new DependencyInjectionContractResolver(services.BuildServiceProvider(),
new[] { typeof(ITestInterface) } );
o.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
});
}