Home > Software design >  What is the MassTransit pattern for retrieving RabbitMQ password from a dependency?
What is the MassTransit pattern for retrieving RabbitMQ password from a dependency?

Time:12-22

Using MassTransit.RabbitMq 8.0.9, in a .Net Core 3.1 project using AspNetCore 3.1.10 and IServiceContainer. The password for RabbitMq is stored in a secrets vault, accessible from a dependency-injected interface. All of the examples I've been able to find just get the password from configuration.

I'd like to do something like

var secrets = serviceProvider.GetRequiredService<ISecretRetrieval>();
var rabbitPassword = secrets.GetRabbitMqPassword();

and then hand that password to IRabbitHostConfigurator, but inside UseMassTransit...UseRabbitMq, there isn't an IServiceProvider instance that I've seen. Alternatively, I could create a configuration object with a constructor-injected dependency on ISecreteRetrieval. I see examples for IConfiguration<MassTransitHostOptions> that show how to create and register my own class with its own constructor dependencies. Can I do that with IConfiguration<RabbitMqHostSettings> even though RabbitMqHostSettings is an interface, not a class like MassTransitHostOptions?

CodePudding user response:

In the UsingRabbitMq block, the first parameter is a service provider.

x.UsingRabbitMq((context, cfg) =>
{
    var secrets = context.GetRequiredService<ISecretRetrieval>();

    cfg.Host("hostname", h =>
    {
        h.Password(secrets.GetRabbitMqPassword());
    });
});
  • Related