injecting a service into a queue consumer using MassTransit

106 views Asked by At

I have a consumer that is configured like follows

.ConfigureServices((hostContext, services) =>
{
    services.AddMassTransit(cfg =>
    {
        cfg.AddConsumer <Consumers>();
        cfg.UsingRabbitMq((context, cfgss) =>
        {
            cfgss.Host(new Uri("rabbitmq://localhost/"), hostss =>
            {
                hostss.Username("guest");
                hostss.Password("guest");
            });

            cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
            {
                //configureEndpoint.ConfigureConsumer<Consumers>(context);
                configureEndpoint.Consumer<Consumers>();
            });

            cfgss.ConfigureEndpoints(context);
        });
    });
})

The services are created with Autofac on a ContainerBuilder and EventService is the service that should be injected into the consumer

var host = new HostBuilder()
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); })
    .ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddJsonFile("appsettings.json", optional: false);
    })
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterType<EventService>().As<IService>();
}

And this is the consumer

public Consumers() { }
    
public Consumers(IService EventService)
{
    _eventsService = EventService;
}

public Task Consume(ConsumeContext<Msg> context)
{
    _eventsService.ProcessInternal(context.Message);
    return Task.CompletedTask;
}

Whenever the message is received, the empty constructor is called but the _eventsService is null

2

There are 2 answers

5
blu3f1rest0rm On BEST ANSWER

I found the solution in this thread

Link

Needed to add the consumer to the config and AddMassTransitHostedService

this is the final working configuration:

services.AddMassTransit(cfg =>
{
    cfg.AddConsumer<Consumers>();
    cfg.UsingRabbitMq((context, cfgss) =>
    {
        cfgss.Host(new Uri("rabbitmq://localhost/"), hostss =>
        {
            hostss.Username("guest");
            hostss.Password("guest");
        });

        cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
        {
            configureEndpoint.ConfigureConsumer<Consumers>(context);
        });

        cfgss.ConfigureEndpoints(context);
    });
});
services.AddMassTransitHostedService();
1
Chris Patterson On

You should be using ConfigureConsumer:

cfgss.ReceiveEndpoint("Queue_Name", configureEndpoint =>
{
    configureEndpoint.ConfigureConsumer<Consumers>(context);
});

And remove the empty constructor entirely.