Skip to content

What is a message mapper?

Sunny Ahuwanya edited this page Jan 26, 2016 · 8 revisions

A message mapper is a class that implements the IMessageMapper interface. It instructs the RestBus client where to route a message to.
A message mapper also provides an instance of a MessagingConfiguration class which instructs the client how to process the message.

A BasicMessageMapper class is provided in the library. It maps messages to the service work queue and provides a MessagingConfiguration that sends transient, expiring, RPC-style messages.

Custom message mappers are useful if you wish to tweak the default messaging behavior. You can create all sorts of message mappers, including send-only message mappers or message mappers that only queue persistent messages in a durable queue.

Message mappers can inspect each message and decide how a message should be routed or processed, based on the content of the message.

For example, here is a message mapper that checks if the message url contains /log/ in it, in which case it's a one way message. The client will not wait for a reply, and the receiving subscriber won't send a response.

class MyMessageMapper : BasicMessageMapper
{
    public MyMessageMapper(string amqpHostUri, string serviceName) : base(amqpHostUri, serviceName)
    {
    }

    public override MessagingConfiguration MessagingConfig
    {
        get
        {
            return new MessagingConfiguration
            {
                MessageExpectsReply = (m) => { 
                    if(m.RequestUri.PathAndQuery.Contains("/log/"))
                    {
                        return false; //Log Messages are not replied to
                    }
                    return true;
                } 
            };
        }
    }
}

For more sophisticated message mappers, the RequestOptions class has a Tag property which can be set to a custom object when the message is being sent:

public class MessageAttributes
{
    public bool Reply { get; set; }
}

//....

var res = await client.PostAsJsonAsync("api/example/", msg, new RequestOptions { Tag = new MessageAttributes { Reply = false } });

You can then inspect the Tag property in the message mapper like this:

MessageExpectsReply = (m) => {
    var requestOptions = GetRequestOptions(m);
    if(requestOptions != null)
    {
        var attributes = requestOptions.Tag as MessageAttributes;
        if(attributes != null)
        {
            return attributes.Reply;
        }
    }

    return true;
}