I'm creating an application using RabbitMQ.Client.Core.DependencyInjection as a consumer of messages in the BackgroundService. Receiving and deserializing the message works correctly, but when I'm sending command to the MediatR I got an error:

 ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder Lifetime: Singleton ImplementationType: RabbitMQ.Client.Core.DependencyInjection.Services.MessageHandlerContainerBuilder': Cannot consume scoped service 'Application.Common.Interfaces.IDbContext' from singleton 'RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder'.
 ---> System.InvalidOperationException: Cannot consume scoped service 'Application.Common.Interfaces.IDbContext' from singleton 'RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder'.

My Command's Handler's constructor is creating dbContext in the constructor, and outside the BackgroundService it works correctly.

I understand that for BackgroundService one needs to create scope and get service from the ServiceProvider:

using var scope = _sp.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<IDbContext>();

But how can I use the rest of the application, where I'm using injected services as singletons?

I believe the same issue would happen if I would call a Service class that constructs injected dbContext in the same way, it does not seem to be a problem with a MediatR.

1

There are 1 best solutions below

1
Tommix On

ok, found a problem with RabbitMQ.Client.Core.DependencyInjection NuGet, instead used RabbitMQ.Client and all works as expected