What's the point of a DataContract in WCF?

VS.net creates a template when you create a WCF project.

It adds a class to the iService1.cs file:

// Use a data contract as illustrated in the sample below to
// add composite types to service operations.
[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Since a WCF service can return any user defined class, why use a DataContract and CompositeType class?

I can return something like:

 [OperationContract]
MyUserCollection GetUsers();

What am I missing?


Solution 1:

The DataContract is just a formal definition of a type that can be understood on both sides of the service boundary.

If you return, as in your example, a "MyUserCollection" object, the consumers of your service will need to reference the innards of your service/system, which is a violation of the SOA tenet of explicit boundaries. By using a DataContract, you are publishing the structure of your return types in a loosely-coupled way.

Solution 2:

Another interesting thing to notice, is if you decorate your code with DataContract, you have a lot of control about what the client can see and must send back to your service. For example:

[DataContract]
public class SampleClass
{
    [DataMember(IsRequired=true)]
    public int MyRequiredProperty { get; set; }

    [DataMember]
    public int MyOptionalProperty { get; set; }

    public int MyInternalProperty { get; set; }
}

On the example above, you defined that when receiving data, you MUST have MyRequiredProperty, and you can have or not MyOptionalProperty. Also, the client will never see MyInternalProperty (this can be for example some property that helps with your logic internally, but you don't want it being exposed at the client level).