Monday, February 10, 2014

How to fix WCF Contract Namespace mismatch on Domain and Client Entities

Wow. every sub domain I was looking for is taken. Some are active and some are just dead without even a single post.

I'm just gonna start this with a WCF problem I've came up with today. and it directly correlates to my blog url.

There are 2 ways as far as I know to make a WCF client.

  1. Use the "Add Service Reference..." dialog. 
  2. Use a custom implementation.
Using the 1'st method is easy and less error prone and it's even so much easier to update.

I'm talking about an issue we face when we try to build a custom implementation. If you are a control freak like me, then you might hit this roadblock sooner or later.

Here's a corresponding StackOverflow Question (Custom object returning as “empty” from WCF?) for this particular solution I'm about to give you.


PROBLEM

When the namespaces are different from Domain/Business data objects (Decorated with [DataContract] attribute) and Client Side data objects, When you run the client, An object with default/empty values are returned. However, from server side, you get the actual data. 

To further illustrate, I have 2 projects with different namespaces.
  1. MyProject.Business.Entities (Marked with [DataContract])
  2. MyProject.Client.Entities (Client side entities to represent business objects)
Q. Why is this happening?
A. 'ContractNamespace' mismatch

Fixes

Use the AssemblyInfo.cs and add following line to each Business and Client projects.
[assembly: ContractNamespace("http://www.tempuri.org/MyProject",
                              ClrNamespace = "MyProject.Business.Entities")]

[assembly: ContractNamespace("http://www.tempuri.org/MyProject",
                              ClrNamespace = "MyProject.Client.Entities")]
Alternatively, you can do this also.
[DataContract (Namespace = "http://www.tempuri.org/MyProject")]
public class Account
{}