Search code examples
silverlightwcfsilverlight-4.0datacontract

Silverlight client, datacontract, and private readonly members


I have a Silverlight client and a WCF service that I want to have share a class:

[DataContract]
public class DatesAreFun
{
  [DataMember]
  private readonly DateTime _date;

  [DataMember]
  private readonly bool _isFun;

  public DateTime DateTime { get { return _date; } }
  public bool IsFun { get { return _isFun; } }

  public DatesAreFun(DateTime date, bool isFun)
  {
    _date = date;
    _isFun = fun;
  }
}

The WCF side seems to send the appropriate data across the wire just fine, but the Silverlight side doesn't like it one bit. It is treating the WCF service DatesAreFun class as a different class than my DatesAreFun class.

Any suggestions on how best to remedy this? Thanks!


Solution

  • This is a common issue and has been covered here more than a few times.

    When you add your service reference, make sure you click the Advanced button, then ensure you have ticked the Reuse types in referenced assemblies checkbox, and selected the Reuse types in all referenced assemblies option.

    You also have to create a new class library assembly that targets the Silverlight runtime. This is because the class library referenced by the WCF services will target the full (or maybe the client profile) version of the .Net framework, which a Silverlight assembly cannot do (in fact a Silverlight assembly can only reference other Silverlight targeted assemblies). In your new class library you can reference the same physical files that the full version of the class library is using, this is detailed more here (i had the same question once upon a time...). You could also pick your way through this bunch of search results for related questions.

    Depending on how you do things you may find you also have to trawl through the Reference.cs file of the Service Reference, and change the namespaces of the named data entities. (This file will get regenerated if you update or reconfigure the service reference).