Setting the default namespace just once for your (data) contracts in WCF

While browsing around the WCF REST starter toolkit I found this attribute:

[assembly: ContractNamespace()]

So what does it do? Well, normally if you don’t specify an explicit namespace in your datacontract, the DataContractSerializer uses its own default, namely generated from the CLR namespace. For example this datacontract:

namespace U2U.DataContracts {   [DataContract]   public class Person   {     [DataMember]     public string Name { get; set; }      [DataMember]     public Job Occupation { get; set; }   }    [DataContract]   public class Job   {     [DataMember]     public string Description { get; set; }   } }

will be serialized like this:

<Person xmlns="http://schemas.datacontract.org/2004/07/U2U.DataContracts"          xmlns:i="http://www.w3.org/2001/XMLSchema-instance">   <Name>Jefke</Name>   <Occupation>     <Description>Developer</Description>   </Occupation> </Person>

But if you use the ContractNamespace attribute:

[assembly: ContractNamespace("http://www.u2u.be/samples/wcf/2009", ClrNamespace = "U2U.DataContracts")]  namespace U2U.DataContracts {   [DataContract]   public class Person   { … }    [DataContract]   public class Job   { … } }

The output now looks like this:

<Person xmlns="http://www.u2u.be/samples/wcf/2009"          xmlns:i="http://www.w3.org/2001/XMLSchema-instance">   <Name>Jefke</Name>   <Occupation>     <Description>Developer</Description>   </Occupation> </Person>

The attribute requires two things, the first is the default namespace to use, the second is the CLR namespace of your datacontract. If you have multiple CLR namespaces for your  data contracts, you will need to repeat this attribute for each namespace. For example:

[assembly: ContractNamespace("http://www.u2u.be/samples/wcf/2009", ClrNamespace = "U2U.DataContracts")] [assembly: ContractNamespace("http://www.u2u.be/samples/wcf/2009", ClrNamespace = "U2U.Jobs")]  namespace U2U.DataContracts {   [DataContract]   public class Person   {     [DataMember]     public string Name { get; set; }      [DataMember]     public Job Occupation { get; set; }   } }  namespace U2U.Jobs {   [DataContract]   public class Job   {     [DataMember]     public string Description { get; set; }   } }
will give you the same output as the previous example.
Comments are closed