nservicebus消息序列化
我想使用一个基消息类,例如:
[Serializable]
public abstract class MessageBase : IMessage
{
public Guid MessageID { get; private set; }
public DateTime UtcDateTime { get; private set; }
protected MessageBase()
{
UtcDateTime = DateTime.UtcNow;
MessageID = Guid.NewGuid();
}
public override string ToString()
{
return string.Format("{0} MessageID={1}, UtcDate={2}", GetType().FullName, MessageID, UtcDateTime);
}
}
新消息将通过从此基类进行子类化来创建。这是我观察到的问题。当我发布消息时,我发现处理消息时消息 ID 和日期时间不同。
我缺少什么?
I would like to use a base message class like:
[Serializable]
public abstract class MessageBase : IMessage
{
public Guid MessageID { get; private set; }
public DateTime UtcDateTime { get; private set; }
protected MessageBase()
{
UtcDateTime = DateTime.UtcNow;
MessageID = Guid.NewGuid();
}
public override string ToString()
{
return string.Format("{0} MessageID={1}, UtcDate={2}", GetType().FullName, MessageID, UtcDateTime);
}
}
New messages will be created by subclassing from this base class. Here is the problem I observed. When I publish a message, I see that the message id and datetime is different when it is handled.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道您想使用私有设置器声明 MessageID 和 UtcDateTime ,以便其他人无法更改它,但这样做可以防止序列化程序在接收方重建消息时重新应用这些值。
发生的情况是,序列化程序实例化消息类型的新实例,并且您的两个属性被初始化为 UtcNow 和 NewGuid(),然后不会从消息中覆盖。这就是为什么它们看起来不同。
如果从属性声明中删除 private 关键字,您应该会得到您期望的行为。
然而,您不应该像这样烘焙自己的跟踪机制,您至少应该(假设您已将 IBus 注入到处理程序中)看一下 Bus.CurrentMessageContext,其中包含正在处理的消息的“Id”属性(字符串、不是 Guid)和 headers 集合。我不能 100% 确定,但如果您检查标头,可能会发现其中有一些原始发送时间的指示。
I know you want to declare MessageID and UtcDateTime with private setters so that someone down the line can't change it, but in doing so, you prevent the serializer from re-applying those values when the message is reconstructed at the receiver.
What is happening is that the serializer instantiates a new instance of your message type, and your two properties are initialized to UtcNow and NewGuid(), and then aren't overridden from the message. This is why they appear different.
If you remove the private keyword from the property declaration, you should get the behavior you are expecting.
However, instead of baking your own tracking mechanisms like this, you should at least (assuming you have injected an IBus into your handler) take a look at Bus.CurrentMessageContext, which contains an "Id" property for the message being handled (string, not Guid) and a Headers collection. I'm not 100% certain, but if you inspect the headers there is probably some indication of the original send time in there.