IEnumerable Return types in WCF

Article covers problems in using IEnumerable as return types in WCF. It covers why Interfaces are not a good choice as return types while developing interoperable WCF Services. Article explains the behavior of DataContractFormatSerializer and it's role in emitting XML which is interoperable

IEnumerable as Return types in WCF

Usually in programming its considered best practice to return an interface or to return a parent type of an object. Reason behind this best practice is to promote extensibility during maintenance phases and will require fewer changes in the code. For e.g it is better to return Person rather than it's two derived types which are Employee and Student.Your system in future can easily take care of the third type say 'Professor' which becomes sub class of the Person class.

This holds true while working with collections as well. In C#, its's always good if you return ICollection or IEnumerable types but this practice of returning base types specially interfaces does not go well with WCF.

I have encountered weird errors while trying to return Interfaces from WCF. After working on WCF for a while I hold a opinion that returning Interfaces from WCF Services is actually a wrong design.

As most of us will be aware that WCF uses a message passing system - it serializes calls and return values into XML serialized messages.

As such, it can only deal with stuff that can be expressed in XML schema - and interfaces aren't expressible in XML schema. DataContractFormatSerializer. which is the default object serializer generates the serialized data that does not contain information about the .NET CLR type from which this data was serialized. This makes perfect sense while looking for interoperability between different platforms.

So at times you might feel what's wrong if I need to return IEnumerable to my client and you get some error like An existing connection was forcibly closed by
the remote host

So problem is not with the code but the behavior of the Serializer which emits the XML that can then be easily deserialized by non .NET clients as well.

Although if interoperability is not required and you are working in a tighter environment then there is a workaround with NetDataContractFormatSerializer
. I would rather keep that one as a seperate article with some niece pieces of example and code



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: