Adam Mills
Adam Mills

Reputation: 8109

How can you do message interception in MassTransit?

I want to inspect each message before it hits consumers or sagas. I think I want an IInboundMessageInterceptor but I can't see an easy way to inject a custom one. How can I achieve message interception in MT? And/Or how can I configure the bus with a custom IInboundMessageInterceptor?

Upvotes: 3

Views: 1914

Answers (1)

Adam Mills
Adam Mills

Reputation: 8109

You can do the following. Your interceptor must implement IInboundMessageInterceptor

  Bus.Initialize(sbc =>
            {
                // ... Initialise Settings ...

                var busConfiguratorr = new PostCreateBusBuilderConfigurator(bus =>
                    {

                        var interceptorConfigurator = new InboundMessageInterceptorConfigurator(bus.InboundPipeline);
                        interceptorConfigurator.Create(new MyIncomingInterceptor(bus));
                    });

                sbc.AddBusConfigurator(busConfiguratorr);
            });

You can then write an interceptor like so

    internal class MyInboundInterceptor : IInboundMessageInterceptor
{
    public MyInboundInterceptor(ServiceBus bus)
    {

    }

    public void PreDispatch(IConsumeContext context)
    {
        IConsumeContext<AwesomeCommand> typedContext;
        if (context.TryGetContext(out typedContext))
        {
            // Do SOmething with typedContext.Message
        }
    }

    public void PostDispatch(IConsumeContext context)
    {
    }
}

Upvotes: 4

Related Questions