What is best approach to create 2 identical copy from CreateBufferedCopy in WCF ?
approach 1 or approach 2 and why?
enter code here
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
//approach 1
Message message1 = buffer.CreateMessage();
Message message2 = buffer.CreateMessage();
//approach 2
Message message1 = request;
Message message2 = request;
foreach (MessageHeader h in message1 .Headers)
{
Console.WriteLine("\n{0}\n", h);
}
return null;
}
Messages in WCF are read-once. This is because they may be streamed and therefore the streamed data will not be magically resent
To “process” a message more than once you have to copy it and the only way to copy it is to use a MessageBuffer as you have in approach 1. Processing a message may be just inspecting the body to perform data dependent routing of the content but as soon as you are going to touch the body you must copy it for the message to be successfully processed by the rest of the WCF infrastructure
Note that if all you want to do is look at the headers you do not need to copy the message as headers are always buffered – it is only the body that is potentially streamed
as @hyp says, approach 2 does not copy the message at all – it just gives you two references to the same message – it may be worth rereading something about reference types and value types – here’s an article that may help