Pages

Tuesday, May 13, 2014

Using NServiceBus Serialization

While working on a project, we had a requirement to send a message to a NServiceBus hosted queue. We realized that normal sending of message to that queue does not work as NServiceBus wraps some header on the message. This either mean we need to send a message using NServiceBus or create an application that uses Bus.Send. Unfortunately we don't want to use Bus.Send so we just re-used the XMLSerialization of NServiceBus.

Here's the code :



           MyMessage walletMessage = new MyMessage ();
          IMessageMapper messageMapper = new MessageMapper ();
          Type type = messageMapper.GetMappedTypeFor( typeof( MyMessage ));
            messageMapper.Initialize( new[] { type });
         NServiceBus.Serialization.IMessageSerializer messageSerializer 
                              = new XmlMessageSerializer (messageMapper);
          using ( Stream stream = new MemoryStream ()){ 
               messageSerializer.Serialize( new object[] {
                                            walletMessage }, stream); 
               stream.Position = 0;
               var sr = new StreamReader (stream);
               var variableToSendToQueue = sr.ReadToEnd();            
         }

2 comments: