我有一个特殊的标题,我想附加到我发布的所有消息.我可以通过在Publish
调用中指定它来逐个添加此标头:
_bus.Publish(myMessage, context => context.SetHeader("my key", "my value"));
这样可以正常工作,但是SetHeader
为每次发布维护此调用都变成了一件苦差事.在总线配置期间或其他任何地方,有没有办法指定将附加到所有消息的标头?也就是说,有没有办法做以下事情?
ServiceBusFactory.New(sbc => { sbc.UseRabbitMq(); sbc.ReceiveFrom(hdoQueue); // This is what I'd like to be able to do: sbc.BeforePublish(context => context.SetHeader("my key", "my value")); });
我相信有一个解决方案涉及实现,IOutboundMessageInterceptor
但我找不到一种方法来附加我的拦截器.有ServiceBusConfigurator.AddInboundInterceptor
方法但不是ServiceBusConfigurator.AddOutboundInterceptor
方法.
我的直觉是正确的,我能够通过实施我想做的事情IOutboundMessageInterceptor
:
public class AttachHeadersOutboundInterceptor : IOutboundMessageInterceptor { public void PreDispatch(ISendContext context) { context.SetHeader("my key", "my value"); } public void PostDispatch(ISendContext context) { } }
奇怪的是不存在ServiceBusConfigurator.AddOutboundInterceptor
的方法,所以我刚创建一个(通过复制所述代码用于AddInboundInterceptor
从GitHub):
public static class MassTransitExtensions { public static void AddOutboundInterceptor(this ServiceBusConfigurator configurator, IOutboundMessageInterceptor interceptor) { var builderConfigurator = new PostCreateBusBuilderConfigurator(bus => { var interceptorConfigurator = new OutboundMessageInterceptorConfigurator(bus.OutboundPipeline); interceptorConfigurator.Create(interceptor); }); configurator.AddBusConfigurator(builderConfigurator); } }
然后我在总线配置期间附加它:
ServiceBusFactory.New(sbc => { sbc.UseRabbitMq(); sbc.ReceiveFrom(hdoQueue); sbc.AddOutboundInterceptor(new AttachHeadersOutboundInterceptor()); });
问题解决了.