Obtain dynamic object in MassTransit consumer

2019-07-10 16:20发布

We use an empty marker interface for a group of events that need to be saved to some audit log database.

However, in the consumer, messages are cast to this interface, so we get an empty object.

What we actually need is to get the "dynamic" or get hold on the message body so we can send it to the audit database "as-is" since our database can save JSON documents. But we cannot see how we can get the message body as JSON from the context. Is it possible at all?

标签: masstransit
1条回答
贪生不怕死
2楼-- · 2019-07-10 16:57

If you really wanted to be efficient, you could keep your consumer using the interface as it is today, but then, in your consumer, get the JToken from the message context, and use the JToken to save the JSON of the message. This way, your consumer doesn't need to know every single object type nor have the assembly for that object type.

public async Task Consume(ConsumeContext<IEvent> context)
{
    ConsumeContext<JToken> jsonContext;
    if(context.TryGetMessage(out jsonContext))
    {
        _eventStore.Save(jsonContext.Message); // the JToken
    }
}
查看更多
登录 后发表回答