0

I have a controller method with the following signature

[HttpGet]
[Route("results")]
public List<IResult> GetResults()
{
  return repo.GetResults();
}

Not surprisingly, I get a JSON .NET exception saying JSON .NET can't resolve IResult to a concrete type. Is there a way to provide JSON .NET the concrete class (Result) so I don't have to change the singature of the method?

Brian
  • 6,910
  • 8
  • 44
  • 82
  • Unless I am misunderstanding your comment, that would require me changing the signature of the method. I've done that already, but what I'd like to do is do some sort of mapping like in an IoC container that says "Always resolve IResult to Result". – Brian Jun 25 '14 at 16:04
  • Not that it helps, just a link to a similar (currently unanswered) question: http://stackoverflow.com/questions/24124176/mvc-web-api-binding-model-to-a-derived-class. – djikay Jun 25 '14 at 17:18

1 Answers1

2

It seems like what you want to do isn't really dependency injection but instead you want to control how the data is serialized. This is completely within your control using a custom media-type formatter (http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters), however you would need to remove the default json formatter first (http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter).

This can all be done however it will makes things more brittle and is probably not the solution you want. It won't work if the client wants xml (you could replace that formatter too). But more importantly, what happens if you have two implementations of the Interface registered in your container? This brings up another question, why are you using an interface as a DTO? An interface typically defines a collection of methods to be implemented by a consumer. I understand that properties can also be defined, but I don't think this is an intended use of interfaces.

Gary.S
  • 7,076
  • 1
  • 26
  • 36
  • I agree with you. I wouldn't want to remove the default formatters, but that may well be the only option. The only reason I used interfaces instead of concrete types is that's how the repositories are set up, and that works nicely for testing with mock data. That is not relevant for the controllers though. The only good reason to use the interfaces would be to avoid having to convert everything to concrete types. – Brian Jun 25 '14 at 17:44