serializationwcfdatacontractserializerdatacontract

How to serialize a derived type as its base type with WCF


I have a common library with some objects in it. Then I have a service project that references the common library and creates some derived types from objects in the common library.

I want my service to serialize the derived types as their base types defined in the common library.

I cannot use KnownTypes on the objects in the common library because I don't want the common library referencing the service assemblies.

So how can I have wcf serialize the derived types as their base types?

I wish I could do something like...

[DataContract(SerializeAsType = typeof(BaseType))] public class DerivedType : BaseType { }

Is anything like this possible?


Solution

  • Are you using .NET 4.0? You can use the DataContractResolver for this if you are:

    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractresolver.aspx

    This is also basically what Entity Framework 4.0 does for its DataContractResolver for proxy types.

    Here is an example: Link

    (see DeserializeAsBaseResolver in the link).

    EDIT: If you're not using .NET 4.0, I think your next best option is a DataContractSurrogate: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx. ...so you can control the serialization by hand, but this can get messy.

    Both are passed into the constructor of your DataContractSerializer and can be configured for WCF via the DataContractSerializerOperationBehavior: http://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx.