Monday, February 7, 2011

ServiceKnownType on WCF


Back after a long time! Work keeps me off from all other work that I “want” to do J

Ok, on this post I would be explaining on a wcf data contract which is not used on any of the methods. Wondering what is special? When you have a data contract and not used for any messages, the client proxy will not create that class at all. That means, either you create that class on your client to use it or find a way to get that method on your proxy class.

I had a situation where I had a method which would accept parameter as Object.  And based on another parameter I decide on object which is passed by the client.

Account GetAccount(GetAccountBy by, object value);

So if by parameter is Name, I was expecting name of Account and the Type of account to search. So my Datacontract

[DataContract]
  [Serializable]
  public class AccountName
  {
    public AccountName()
    {
    }
    public AccountName (string name, AccountType type)
    {
      this.Name = name;
      this.Type = type;
    }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public AccountType Type { get; set; }
  }

When I add GetAccount method on my service and expose to client, the AccountName was never getting reflected on the client proxy.  This was because it’s not referred directly on any of the methods and client doesn’t know how to pick that.

To get this class on client, I had to add an attribute

[ServiceKnownType(typeof(AccountName))]
On the service and regenerate the proxy.