Skip to content

No working way for UseCase Aspire+MassTransit+RabbitMq+MessagePackSerializer #663

Closed

Description

@migoldfinger

Describe the bug

Hi,
I am in dire need of a working example of how to get the Weather Forecast template running with MassTransit.
I got it to work without MassTransit already, so the Messages are working fine.
I hit dead ends all the time. I think I have found a way for the Consumer side but the website gives me a headache.
I use the Packages

    <PackageReference Include="CommunityToolkit.Aspire.MassTransit.RabbitMQ" Version="9.4.0" />
    <PackageReference Include="MassTransit.MessagePack" Version="8.4.0" />
    <PackageReference Include="MessagePack" Version="3.1.3" />

I have defined 2 Messages WeatherRequestMessage and WeatherResponseMessage.
My Problem on the Webapplication
I want to use a specific Exchange and RoutingKey when I send the RequestMessage
This code should be enough if the rest is configured correctly

namespace My.Web;

using MassTransit;
using Messages.Weather;

public sealed class WeatherApiClient(ILogger<WeatherApiClient> logger, IRequestClient<WeatherRequestMessage> requestClient)
{
	public async Task<WeatherResponse[]> GetWeatherAsync(int maxItems = 10, CancellationToken cancellationToken = default)
	{
		Response<WeatherResponseMessage> response = await requestClient.GetResponse<WeatherResponseMessage>(new WeatherRequestMessage(), cancellationToken).ConfigureAwait(false);
		logger.LogInformation("Published message to requestClient");

		return response.Message.WeatherForecastArray;
	}
}
}

in Program.cs i tried something like this but that gives me errors

builder.AddMassTransitRabbitMq("MessageBus",
                               static settings => { settings.DisableTelemetry = false; },
                               static config =>
                               {
	                               config.UsingRabbitMq(static (context, cfg) =>
	                                                    {
		                                                    var configuration = context.GetRequiredService<IConfiguration>();
		                                                    string? host = configuration["RabbitMQ:Host"];
		                                                    cfg.Host(host);
		                                                    cfg.UseMessagePackSerializer();
		                                                    cfg.AddPublishMessageTypes([typeof(WeatherRequestMessage)],
		                                                                               (configurator, type) =>
		                                                                               {
			                                                                               configurator
				                                                                               .BindQueue(configuration["RabbitMQ:RequestExchange"]!,
					                                                                               configuration["RabbitMQ:RequestRoutingKey"]);
		                                                                               });
	                                                    });
                               });

Regression

No response

Steps to reproduce

All examples found that uses Aspire+MassTransit do not even mention the builder.AddMassTransitRabbitMq extension.

Expected behavior

A working example for this common use case.

Screenshots

No response

IDE and version

VS 2022

IDE version

No response

Nuget packages

<PackageReference Include="CommunityToolkit.Aspire.MassTransit.RabbitMQ" Version="9.4.0" />
  <PackageReference Include="MassTransit.MessagePack" Version="8.4.0" />
  <PackageReference Include="MessagePack" Version="3.1.3" />

Additional context

No response

Help us help you

No, just wanted to report this

Activity

  1. migoldfinger commented on Apr 30, 2025

    @migoldfinger
    Author

    Partial success I was able to register MassTransitSerializer, I just had to write an own custom extension

    public static class CustomExtensions
    {
    	public static void AddMassTransitRabbitMq(this IHostApplicationBuilder builder,
    		string name,
    		Action<MassTransitRabbitMqSettings>? configureOptions = null,
    		Action<IBusRegistrationConfigurator>? massTransitConfiguration = null,
    		Action<IRabbitMqBusFactoryConfigurator>? rabbitMqConfiguration = null
    	)
    	{
    		AddMassTransitRabbitMq<IBus>(builder, name, configureOptions, massTransitConfiguration, rabbitMqConfiguration);
    	}
    
    	public static void AddMassTransitRabbitMq<TBus>(this IHostApplicationBuilder builder,
    		string name,
    		Action<MassTransitRabbitMqSettings>? configureOptions = null,
    		Action<IBusRegistrationConfigurator>? massTransitConfiguration = null,
    		Action<IRabbitMqBusFactoryConfigurator>? rabbitMqConfiguration = null
    	)
    		where TBus : class, IBus
    	{
    		ArgumentNullException.ThrowIfNull(builder);
    		ArgumentNullException.ThrowIfNull(name);
    		ArgumentException.ThrowIfNullOrWhiteSpace(name);
    
    		var options = new MassTransitRabbitMqSettings();
    		configureOptions?.Invoke(options);
    		string? rabbitMqConnectionString = builder.Configuration["ConnectionStrings:" + name];
    
    		if (string.IsNullOrWhiteSpace(rabbitMqConnectionString))
    		{
    			throw new InvalidOperationException("RabbitMQ connection string is missing or empty in configuration.");
    		}
    
    		GlobalTopology.Send.UseRoutingKeyFormatter<WeatherRequestMessage>(static x => string.Empty);
    		GlobalTopology.Send.TryAddConvention(new RoutingKeySendTopologyConvention());
    
    		builder.Services.AddMassTransit<TBus>(x =>
    		                                      {
    			                                      x.SetKebabCaseEndpointNameFormatter();
    			                                      x.SetInMemorySagaRepositoryProvider();
    			                                      var entryAssembly = Assembly.GetEntryAssembly();
    			                                      x.AddSagaStateMachines(entryAssembly);
    			                                      x.AddSagas(entryAssembly);
    			                                      x.AddActivities(entryAssembly);
    
    			                                      massTransitConfiguration?.Invoke(x);
    
    			                                      x.UsingRabbitMq((context, cfg) =>
    			                                                      {
    				                                                      cfg.Host(new Uri(rabbitMqConnectionString));
    				                                                      cfg.ConfigureEndpoints(context);
    				                                                      rabbitMqConfiguration?.Invoke(cfg);
    			                                                      });
    		                                      });
    
    		if (!options.DisableTelemetry)
    		{
    			builder.Services
    			       .AddOpenTelemetry()
    			       .WithMetrics(static b => b.AddMeter(DiagnosticHeaders.DefaultListenerName))
    			       .WithTracing(static providerBuilder => { providerBuilder.AddSource(DiagnosticHeaders.DefaultListenerName); });
    		}
    	}
    }
    

    I then could call in Program.cs

    builder.AddMassTransitRabbitMq("MessageBus",
                                    massTransitConfiguration: static configurator =>
                                                              {
    configurator.AddRequestClient<WeatherRequestMessage>();
                                                              },
                                    rabbitMqConfiguration: static configurator =>
                                                           {
    	                                                       configurator.UseMessagePackSerializer();
                                                           });
    

    After that, MessagePack was used. I still struggle to find a way to use existing Exchanges and Queues.

  2. locked and limited conversation to collaborators on May 2, 2025
  3. converted this issue into a discussion #668 on May 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions