Azure 服务总线消息在订阅运行时反序列化为未知类型

Azure Service Bus Message deserialize to an unknown type at runtime in subscriptions

这很令人惊讶,但我还没有找到一个示例,其中在订阅中收到的消息可能是不同的类型,并且需要知道该类型才能使用正确的类型反序列化其内容。 但它没有考虑那种情况

我有一个发布-订阅者场景。对于订阅者,创建可以根据 https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions 使用 Azure 服务总线库发布的 Message 我需要传递一个字节数组。它似乎没有任何自定义元数据之类的东西,我可以用它来指定消息或类似的程序集类型。

当订阅收到消息时,它必须反序列化它,但我无法知道具体消息是哪种类型,以便做一个JsonConvert.DeserializeObject<TDestType>(Encoding.UTF8.GetString(message.Body))

有没有人有任何 link 或样本来实现这个?还是仅针对一种类型的消息使用主题和主题订阅的推荐做法? (我对此表示怀疑,但我知道 MassTransit 例如会在幕后为每条消息创建一个主题。)


更新 1:现在我将在消息中使用 ContentType 属性 来存储 EventType,以便订阅者可以使用它来反序列化。但是如果感觉是"hacky"因为这个字段应该是存储格式类型(json、xml等)

It does not seem to have anything like custom metadata that I could use to specify the assembly type for the message or similar.

Azure 服务总线为每条消息提供 headers/metadata 作为 UserProperties 可用。一个主题可以接收多种消息类型,订阅者可以使用订阅查看他们将处理的消息类型。订阅可以是简单的订阅,也可以利用消息的 ContentType 属性 使用 correlation filters or have a more advanced SQL filters 提供更高级的订阅机制。

For now I'll use the ContentType property at the Message to store the EventType so that the suscriptor can use it to deserialize. But if feels "hacky" because this field is supposed to store the format type (json, xml, etc.)

您可以保留 ContentType 用于序列化,并使用自定义 header 为订阅者过滤消息。或者您可以选择将两者都存储在自定义 header 中。由你决定。

It's surprising, but I haven't yet found a sample where the Message received at a subscription could be of different types and the type needs to be known in order to deserialize its content with the right type.

这就是 NServiceBus 使用 Azure 服务总线作为传输方式所做的事情。单个接收器(端点)可以处理不同的消息类型。订户创建过滤器来检查自定义 header 值以确定消息的类型。