问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/24413491/resolving-interfaces-in-webapi