I'm creating a topic exchange with generic event type and 2 different consumers, I would like to know if there is a better way to do this using generics ?
How i'm doing
Generic event:
public interface IOrchestratorTopicType<T> where T : class
{
public Guid? TraceId { get; set; }
public string Event { get; set; }
public string Source { get; set; }
public string Destination { get; set; }
public T Data { get; set; }
}
configuration:
services.AddMassTransit(bus =>
{
bus.SetKebabCaseEndpointNameFormatter();
bus.UsingRabbitMq((ctx, busConfigurator) =>
{
busConfigurator.Host(configuration.GetConnectionString("RabbitMq"));
busConfigurator.Publish<IOrchestratorTopicType<object>>(a => a.ExchangeType = ExchangeType.Topic);
busConfigurator.ReceiveEndpoint("create-order", e =>
{
e.ConfigureConsumeTopology = false;
e.Consumer<CreateOrderConsumer>();
e.Bind<IOrchestratorTopicType<object>>(s =>
{
s.RoutingKey = "create.order";
s.ExchangeType = ExchangeType.Topic;
});
});
busConfigurator.ReceiveEndpoint("valid-order", e =>
{
e.ConfigureConsumeTopology = false;
e.Consumer<ValidOrderConsumer>();
e.Bind<IOrchestratorTopicType<object>>(s =>
{
s.RoutingKey = "valid.order";
s.ExchangeType = ExchangeType.Topic;
});
});
});
});
services.AddMassTransitHostedService();
Producer:
await _publisher.Publish<IOrchestratorTopicType<object>>(new
{
TraceId = new Guid(),
Event = "create.order",
Source = "SourceTestSource",
Destination = "DestinationTest",
Data = createOrderModel
}, e => e.TrySetRoutingKey("create.order"));
Consumers:
public class ValidOrderConsumer : IConsumer<IOrchestratorTopicType<object>>
{
public Task Consume(ConsumeContext<IOrchestratorTopicType<object>> context)
{
throw new NotImplementedException();
}
}
public class CreateOrderConsumer : IConsumer<IOrchestratorTopicType<object>>
{
public Task Consume(ConsumeContext<IOrchestratorTopicType<object>> context)
{
throw new NotImplementedException();
}
}
I would like the producer to send the exact type of the object and the consumer to consume the exact type of the object and not the generic object
CodePudding user response:
I'd suggest watching this video on how MassTransit uses RabbitMQ. There is zero need to use topic exchanges with MassTransit, as it used type-based routing by default.
The code above is not something I'd recommend, since MassTransit already does polymorphic type-based routing by default with RabbitMQ.