MULTIMEDIA

WCF Services : Delegates and Data Contracts

9/23/2010 3:01:15 PM

All delegate definitions are compiled into serializable classes, so in theory your data contract types can contain delegates as member variables:

[DataContract]
class MyDataContract
{
[DataMember]
public EventHandler MyEvent;
}

Or even as events (note the use of the field qualifier):

[DataContract]
class MyDataContract
{
[field:DataMember]
public event EventHandler MyEvent;
}

In practice, however, when the data contract refers to a custom delegate, the imported data contract will contain an invalid delegate definition. While you could manually fix that definition, the bigger problem is that when you serialize an object that has a delegate member variable, the internal invocation list of the delegates is serialized, too. In most cases, this is not the desired effect with services and clients, because the exact structure of the list is local to the client or the service and should not be shared across the service boundary. In addition, there are no guarantees that the target objects in the internal list are serializable or are valid data contracts. Consequently, sometimes the serialization will work, and sometimes it will fail.

The simplest way to avoid this pitfall is not to apply the DataMember attribute on delegates. If the data contract is a serializable type, you need to explicitly exclude the delegate from the data contract:

[Serializable]
public class MyDataContract
{
[NonSerialized]
public EventHandler MyEvent;
}
Other  
 
Most View
The Small Screen Revolution (Part 2)
Windows 8 Hardware (Part 1) : Microsoft Surface RT
Mobile Devices and HDMI
Intex AQUA 5.0 - The Gains Of Deception
LG Optimus L9 - A Cheap Middle Class Android Phone (Part 3)
Sapphire Vapor-X CPU Cooler - Brings Its GPU Inspired Cooling Tech To The CPU Party
Systems for All Budgets (Part 1) - GX250, GX2000
Technology For Business (Part 2)
Something You Should Know About Iphone 5 (Part 2)
MapQuest - Hard To Recommend
Top 10
G.Skill DDR3 SDRAM 32GB Review (Part 6)
G.Skill DDR3 SDRAM 32GB Review (Part 5)
G.Skill DDR3 SDRAM 32GB Review (Part 4)
G.Skill DDR3 SDRAM 32GB Review (Part 3)
G.Skill DDR3 SDRAM 32GB Review (Part 2)
G.Skill DDR3 SDRAM 32GB Review (Part 1)
Macbook Pro With 13in Retina Display Review (Part 3)
Macbook Pro With 13in Retina Display Review (Part 2)
Macbook Pro With 13in Retina Display Review (Part 1)
Kensington Folio Trio For iPad