Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
migoldfinger opened this issue Apr 28, 2025 · 1 comment

Comments

@migoldfinger
Copy link

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

@migoldfinger
Copy link
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.

@CommunityToolkit CommunityToolkit locked and limited conversation to collaborators May 2, 2025
@aaronpowell aaronpowell converted this issue into discussion #668 May 2, 2025

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant