简体   繁体   中英

MSMQ empty object on message body

Ok, so I'm very VERY new to MSMQ and I'm already confused.

I have created a private queue and added a few messages to it, all good so far. BUT when I retrieve the messages back from the queue the message body contains a empty object of the type I added. By this I don't mean that the body is null, it does have a reference to a type of the object that I added, but it's not instantiated so all the properties are in their null or default state.

This is the code I use to add to the queue:

using (var mQueue = new MessageQueue(QueueName))
{
    var msg = new Message(observation)
    {
            Priority = MessagePriority.Normal,
             UseJournalQueue = true,
            AcknowledgeType = AcknowledgeTypes.FullReceive,
    };
    mQueue.Send(msg);
}

And this is the code that dequeues the messages:

using (var mQueue = new MessageQueue(QueueName))
{
    mQueue.MessageReadPropertyFilter.SetAll();
    ((XmlMessageFormatter)mQueue.Formatter).TargetTypes =
                                                  new[] { typeof(Observation) };
    var msg = mQueue.Receive(new TimeSpan(0, 0, 5));
    var observation = (Observation)msg.Body;

    return observation;
}

The Message constructor uses XML serialization to serialize your "observation" object. You'll need to make sure that this works properly. XML serialization will only deal with public members of the class, it is not going to serialize private members. Your object may well look "empty" after it is deserialized again.

Here's some test code to verify that it works properly:

using System;
using System.IO;
using System.Xml.Serialization;

class Program {
  static void Main(string[] args) {
    var ser = new XmlSerializer(typeof(Observation));
    var sw = new StringWriter();
    var obj = new Observation();
    ser.Serialize(sw, obj);
    Console.WriteLine(sw.ToString());
    var sr = new StringReader(sw.ToString());
    var obj2 = (Observation)ser.Deserialize(sr);
    // Compare obj to obj2 here
    //...
    Console.ReadLine();
  }
}
public class Observation {
  // etc...
}

另外,请确保您的自定义Message对象在每个属性上都有公共setters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM