Wednesday, 18 October 2006

Some time ago I have been searching for a solution to a common problem you have dealing with inheritance in web services. The main problem is that if you have a base class: Employee and two sub-classes: Manager and PartTimeEmployee, and you have a WebMethod that returns Employee - then it will not work if you just try to return any of the sub-classes. What you will get is an InvalidOperationException in a form of:

"System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type Manager was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

Fortunately, the error message also provides an information about what should be done: "Use the XmlInclude or SoapInclude attribute". If you have dealt with web services in .NET you have probably encountered this kind of problem and know the solution which is to put the mentionet XmlInclude attribute on the base class - in this case the Employee and specify all the derived types in there as in the example:

public class Employee

This solves the problem of the inheritance only in part. Generally you not always have control over the inheritance structure at the time of writing the Employee class so you cannot use the XmlInclude there. I have found the answer for this problem here. Basicaly what you can do is put the XmlInclude attribute on the web method returning the Employee type. At the time of writing this method, you should have a more complete knowledge about the possible subtypes of the Employee class than you had while creating the class itself. The solution is far from perfect but it is still better than nothing.

There is also an interesting discussion about the issuue on the same page where I have found the article - in the comments section.

kick it on