Reputation: 4789
I am using MassTransit to publish\subscribe messages using RabbitMQ. I want to inject dependencies in dependency in consumers so that consumers can insert data to the database. However, I found the examples in the documentation confusing.
public class MessageConsumer : IConsumer<Message>
{
private IDao dao;
public MessageConsumer(IDao dao)
{
this.dao = dao;
}
public async Task Consume(ConsumeContext<Message> context)
{
Console.WriteLine("Order Submitted: {0}", context.Message.MessageId);
}
}
The bus is configured as follows
static void Main(string[] args)
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<ConcreteDao>().As<IDao>();
builder.RegisterType<MessageConsumer>().As<IConsumer<Message>>();
builder.AddMassTransit(x =>
{
// add the bus to the container
x.UsingRabbitMq((context, cfg) =>
{
cfg.Host("localhost");
cfg.ReceiveEndpoint("MessageQueueName", ec =>
{
// Configure a single consumer
ec.ConfigureConsumer<MessageConsumer>(context);
});
// or, configure the endpoints by convention
cfg.ConfigureEndpoints(context);
});
});
var container = builder.Build();
var bc = container.Resolve<IBusControl>();
bc.Start();
}
However I am getting an exception when the IBusControl is resolved.
System.ArgumentException: 'The consumer type was not found: StationDashboard.Messaging.Consumer.OperationModeChangedConsumer (Parameter 'T')'
What is wrong with the code above? What is the best way to inject dependency to a consumer? It would help if there was a complete working sample.
Upvotes: 1
Views: 2780
Reputation: 33278
You need to register the consumer as explained in the documentation.
Do NOT do this:
builder.RegisterType<MessageConsumer>().As<IConsumer<Message>>();
Instead, as shown in the documentation, do this:
x.AddConsumer<MessageConsumer>();
Your dependency can be registered as you've done it.
Upvotes: 3