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
I found the solution in this thread
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();