2

In .NET 3.5, I would like to create a custom attribute (say [NetDataMember]) that would switch the serialization behavior from DataContractSerializer to NetDataContractSerializer.

Basically, for a class A as illustrated below

[DataContract]
class A
{
  [DataMember]
  public int SimpleProperty { get; set; }

  [Transcient]
  public IBar ComplexProperty { get; set; }
}

I would like to obtain a serializer that would behave like DataContractSerializer by default, but that would be overriden with NetDataContractSerializer for properties marked with [NetDataMember].

Any idea how to design a serializer that would achieve such behavior?

Joannes Vermorel
  • 8,976
  • 12
  • 64
  • 104

1 Answers1

6

There's no "out-of-the-box" way in WCF to do this - but a lot of really smart people have already tackled that problem.

Check out Aaron Skonnard's blog post on the NetDataContractSerializer in which he present a behavior you can put on your data contracts as an attribute:

[NetDataContractFormat] 

on your service interface (for all methods) or on a single method will use the NetDataContractSerializer for that call. You need to define this per operation or service - not on your data contracts.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Thanks for the link. Actually, I can't manage to produce the override effect. I am applying the attribute, but the overriding behavior is never called at (de)serialization time. Am I missing some when instantiating the DCS? – Joannes Vermorel Dec 12 '09 at 09:21
  • When deserializing, in WCF, no constructor is ever called - that's a normal behavior. – marc_s Dec 12 '09 at 09:33
  • But to see whether or not the NetDataContractSerializer is being used, you should look at the messages being sent around - either use the WcfTestClient.exe in your Visual Studio Common7/IDE directory, or use something like Fiddler to view the traffic – marc_s Dec 12 '09 at 09:34
  • @Rabskatran: thanks for pointing out - yes, seems that blog post is gone - can't seem to find it anymore. Check out [this MSDN article](http://msdn.microsoft.com/en-us/magazine/cc163569.aspx) by Aaron Skonnard for explanations - but unfortunately, that doesn't include the `[NetDataContractFormat]` attribute code, sorry... – marc_s Sep 06 '12 at 11:28
  • An archived version of the blog post is here: http://web.archive.org/web/20110814134219/http://www.pluralsight-training.net/community/blogs/aaron/archive/2006/04/21/22284.aspx – dbc Nov 20 '15 at 00:18