When you publish a message through MassTransit to RabbitMQ, a default naming strategy is used to create a corresponding exchange. The default naming convention is the fully qualified name of the message class, so if you have a class named HelloWorldMessage in a namespace MyCompany.Messages.V1, you’ll end up with an exchange named MyCompany.Messages.V1:HelloWorldMessage.
This is ok if you are running RabbitMQ locally(through Docker for example), but it gets quite annoying if you are publishing to a shared infrastructure during development. The problem is that you start receiving messages from other developers which makes debugging a lot more difficult.
To solve this problem I created a custom EntityNameFormatter that allows you to specify an extra environment setting that can be set to for example to a specific username. Doing this in MassTransit 5 is not that hard as you can set this for the whole MessageTopology(something that was not easily done in previous versions).
Here is the required code:
- First, we have to create a custom formatter by implementing the IEntityFormatter interface(note that I’m passing in the original formatter):
class EnvironmentNameFormatter : IEntityNameFormatter | |
{ | |
private IEntityNameFormatter _original; | |
public EnvironmentNameFormatter(IEntityNameFormatter original) | |
{ | |
_original = original; | |
} | |
public string FormatEntityName<T>() | |
{ | |
var environment = ConfigurationManager.AppSettings["Environment"]; | |
return $"{environment}:{_original.FormatEntityName<T>()}"; | |
} | |
} |
- Second, we have to apply this formatter. As I want to do this for all messages, I specify it on the MessageTopology setting:
var bus = Bus.Factory.CreateUsingRabbitMq(sbc => | |
{ | |
var host = sbc.Host(new Uri("rabbitmq://demo:5672"), h => | |
{ | |
h.Username("demo"); | |
h.Password("demo"); | |
}); | |
sbc.MessageTopology.SetEntityNameFormatter(new EnvironmentNameFormatter(sbc.MessageTopology.EntityNameFormatter)); | |
}); |
Now we can specify a different name in our configuration and only receive the messages that we want.
Remark: You have to apply this code both on the send and receive side of your application