Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
Dannerbo Avatar asked Nov 10 '10 03:11

Dannerbo


2 Answers

We have just "solved" this issue by setting inherited class [DataContract(Name="BaseClass")]. It works even if inherited class is internal and defined in another project.

Hope it helps.

like image 93
marc Avatar answered Sep 19 '22 00:09

marc


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.

like image 42
Jeff Avatar answered Sep 19 '22 00:09

Jeff