I have a WCF service which exposes a type TestTypeOne
which currently has a string property called ProductId
:
public class TestTypeOne
{
[DataMember(Name = "ProductId")]
public string ProductId { get; set; } //note it's a string at the moment
}
I want to change the type of this property from string
to a custom value type called ProductId
, but without breaking the WCF contract (this is only for the server side, the clients should see the ProductId
as a string still.)
public class TestTypeOne
{
[DataMember(Name = "ProductId")]
public ProductId ProductId { get; set; }
}
The custom type is something like this (most code removed for brevity):
public struct ProductId : IEquatable<ProductId>
{
readonly string productId;
public ProductId(string productId)
{
this.productId = productId
}
public override string ToString() => productId ?? string.Empty;
}
Using the following test code:
var sb = new StringBuilder();
using (var writer = new XmlTextWriter(new StringWriter(sb)))
{
var dto = new TestTypeOne {
ProductId = new ProductId("1234567890123")
};
var serializer = new DataContractSerializer(typeof(TestTypeOne));
serializer.WriteObject(writer, dto);
writer.Flush();
}
Console.WriteLine(sb.ToString());
The expected output when serializing should be:
<Scratch.TestTypeOne xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Tests">
<ProductId>1234567890123</ProductId>
</Scratch.TestTypeOne>
I have tried implementing ISerializable
but that seems to only let me control the content of the ProductId
xml tag, not the tag itself (so I can make things like <ProductId><something>1234113</something></ProductId>
happen).
Ideally I am after something I can do to the ProductId
type itself, as this type is used in many places, and many contracts.