How do you return a user defined type from a WCF service?

flesh picture flesh · Jan 13, 2009 · Viewed 14.4k times · Source

I have a WCF service hosted in IIS. The intention is for clients to make a call and receive a custom class that is defined in another project/dll. I have generated a service client using the svcutil.exe. The problem is this autogenerated client contains a new partial / proxy definition for the class I am trying to return from the service. It now throws a conversion error between my original custom class and the new partial definition at compile time. So how do you return user defined types from a WCF service? Advice appreciated.

Answer

Andrew Hare picture Andrew Hare · Jan 13, 2009

If the type that you want to return from your service call is not marked as a DataContract then you will not be able to return it from WCF without providing a copy of that same assembly to your client application.

using System;
using System.ServiceModel;

[ServiceContract]
interface IService
{
    [OperationContract]
    TimeSpan GetTimeSpan();
}

class Service : IService
{
    public TimeSpan GetTimeSpan() { return DateTime.Now.TimeOfDay; }
}

Why does the previous code work then? It works because both sides of the service call have System.dll so they both know about the System.TimeSpan type which is the return type of the OperationContract GetTimeSpan().

Here is an example using a DataContract:

using System;
using System.ServiceModel;
using System.Runtime.Serialization;

[ServiceContract]
interface IService
{
    [OperationContract]
    Contract GetContract();
}

[DataContract]
class Contract
{
    [DataMember]
    public String MyProperty { get; set; }
}

class Service : IService
{
    public Contract GetContract() { return new Contract(); }
}

Now you have provided serialization attributes to a class you have defined (Contract) - this will allow you to use svcutil.exe to create proxy classes in your client application that will be serialized and sent to the WCF service.

Now if you want to return a type that is not a DataContract you must provide a copy of the assembly containing that type to your client application.