If you're communicating with WCF via a ClientBase proxy class, you may, at one time or another, have encountered the cryptic exception "The underlying connection was closed: The connection was closed unexpectedly."
If your WCF method is returning something other than void when you encounter this exception, there's a good chance that the problem has to do with an inability to serialize the return value, rather than anything to do with the "underlying connection." This is almost certainly the case if other calls to void-returning-WCF-methods are working just fine. To verify and fix, run the following code example, replacing MyObject with the class that you're returning from the WCF method, to see if the result type will in fact serialize successfully.
MyObject myObject = new MyObject();
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(myObject.GetType());
serializer.Serialize(new MemoryStream(), myObject);
The only limitation to this troubleshooting approach is that if you're using DataContract/DataMember attributes on your properties, then WCF may end up serializing the object successfully while this test code will fail if you're not decorating the culprit property with the DataMember attribute. Accordingly, if you're using DataContract/DataMember attributes, you'll want to decorate unincluded properties with [XmlIgnore] to make the XML serialization test mimic what WCF will be serializing. (Please let me know if you know of a cleaner way to do this without dirtying up the object.)
If you're developing TDD-style (of course you are!), just make a test with this code called CanWcfReturnTypeBeSerialied() or something along those lines. On a related note, for a good resource concerning serializing and deserializing objects in C#, along with a couple of nice helper methods, check out http://www.dotnetjohn.com/articles.aspx?articleid=173.
I've run into this problem enough times (including an hour or so on it today) to blog about it...mostly so that I'll find my own post via Google the next time I run into it!
Billy McCafferty
http://www.itsamuraischool.com
Posted
07-29-2009 2:24 PM
by
Billy McCafferty