1

Headers are published with Azure Service Bus, like below:

 string content = "body";
 await _busPublisher.Activator.Bus.Publish(content, headers);

How to retrieve both header and content on subscriber?

class Handler :  IHandleMessages<string>
    {

    public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }

        public async Task Handle(string message)
        {
            Console.WriteLine("Handle(string message): {0}", message);

        }
    }

Update

Below is one solution. Is this the best solution?

        public Handler(IMessageContext messageContext, ILog log)
    {
        _messageContext = messageContext;
        _log = log;
    }
            public async Task Handle(string message)
            {
                Console.WriteLine("Handle(string message): {0} ", message);
                Console.WriteLine("headers: {0} ", string.Join(' ', _messageContext.Headers));

            }

When a Handler is instantiated like below, is it possible to use dependency injection instead?

        var Activator = new BuiltinHandlerActivator();

        Activator.Register((mc) =>
            {
                return new Handler(mc, log);  //no new?

            }
Pingpong
  • 7,681
  • 21
  • 83
  • 209

1 Answers1

2

Accepted IMessageContext injected into the constructor of your handler is the way to go:

public class Handler : IHandleMessages<string>
{
    readonly IMessageContext messageContext;

    public Handler(IMessageContext messageContext, ILog log)
    {
        this.messageContext = messageContext;
    }

    public async Task Handle(string message)
    {
        var headers = messageContext.Headers;

        // do stuff
    }
}

If you're using BuiltinHandlerActivator, you can have it injected like this:

activator.Register(context => new Handler(context));

or if you also need the IBus in your handler:

activator.Register((bus, context) => new Handler(bus, context));
mookid8000
  • 18,258
  • 2
  • 39
  • 63
  • My question is that is there a way to avoid using this: `new Handler`? as mentioned on the OP. – Pingpong May 30 '19 at 13:21
  • Yes – you do that by choosing a real IoC container. You can read more on the wiki page about IoC containers: [Container adapters](https://github.com/rebus-org/Rebus/wiki/Container-adapters) – mookid8000 May 31 '19 at 11:10