Shared classes and Web Services

The Windows Communication Foundation Services have simplified the way you use classes in distributed application.

Windows Communication Foundation (WCF) expands the .NET WebServices technologies. One exciting feature is the Data Contracts abilities that enables you to marshall data structures more seamlessly through the service. The “classic” .NET WebService (as well as a WCF service) exposes a description in the WebService Description Language. The WSDL file describes the methods supported by the WebService, and the data structures (classes) used by these methods (parameters and results).

When a application consumes the WebService, Visual Studio creates a WebService reference – including a codefile that wraps the service. Each data structure is created as new a class inside the reference. Say you have a WebService with a single method GetPerson that returns a instance of you MyClasses.Person class. After consuming the WebService, the reference codefile will contain a new class, MyServiceReference.Person. This new class contains only the serializable public fields of the original class exposed the the WSDL file.

For a external consumer everything is fine. The external consumer have no knowledge of the original class (or the fancy methods and he/she might be missing). All the external consumer knows and needs to know is the data fields described in the WSDL file – Visual Studio have wrapped these structures in classes – everything is fine.

But in a distributed application, both the WebService and the consuming application may be part of the same application and codebase. But since the WebService still creates new classes in the WebService reference, you end up with two classes representing the same data: On the WebService side you will have your MyClasses.Person and on the consuming side of the WebService you will have your MyServiceReference.Person. And there is (to my knowledge) no easy way to cast the MyServiceReference.Person instance to a full fetched MyClasses.Person class.

This have changed in WCF services: You can now use the DataContract attribute to expose a class through the services WSDL. Likewise each public field must be marked the the DataMember attribute. Now, when you create a reference to the WCF, Visual Studio will (as default) reuse classes in shared assemblies: The result – you will end up with only one version of the applications classes.