Getting ServiceStack to retain type information

Inheritance in DTOs is a bad idea – DTO’s should be as self-describing as possible and by using inheritance clients effectively have no idea what the service ultimately returns. Which is why your DTO classes will fail to de/serialize properly in most ‘standards-based’ serializers.

There’s no good reason for having interfaces in DTO’s (and very few reasons to have them on POCO models), it’s a cargo cult habit of using interfaces to reduce coupling in application code that’s being thoughtlessly leaked into DTOs. But across process boundaries, interfaces only adds coupling (it’s only reduced in code) since the consumer has no idea what concrete type to deserialize into so it has to emit serialization-specific implementation hints that now embeds C# concerns on the wire (so now even C# namespaces will break serialization) and now constrains your response to be used by a particular serializer. Leaking C# concerns on the wire violates one of the core goal of services for enabling interoperability.

As there is no concept of ‘type info’ in the JSON spec, in order for inheritance to work in JSON Serializers they need to emit proprietary extensions to the JSON wireformat to include this type info – which now couples your JSON payload to a specific JSON serializer implementation.

ServiceStack’s JsonSerializer stores this type info in the __type property and since it can considerably bloat the payload, will only emit this type information for types that need it, i.e. Interfaces, late-bound object types or abstract classes.

With that said the solution would be to change Animal to either be an Interface or an abstract class, the recommendation however is not to use inheritance in DTOs.

Leave a Comment