简体   繁体   中英

Injecting dependency to consumers using Autofac in masstransit

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM