I have a RabbitMQ Singleton that is working fine, but has a dependency on a scoped service whenever a message arrives:
consumer.Received += _resourcesHandler.ProcessResourceObject; //Scoped Service
My services are registered like so:
services.AddScoped<IHandler, Handler>();
services.AddSingleton<RabbitMqListener>();
The scoped services constructors uses DI for the Db Context:
private readonly ApplicationDbContext _appDbContext;
public ResourcesHandler(ApplicationDbContext appDbContext)
{
_appDbContext = appDbContext;
}
This scoped service calls the Db Context in order to insert properties to the database on receipt of a message.
However, because the scoped service has a different lifetime, startup is failing.
Is there a better way to do this? I could make the scoped service a singleton, but then I'd have the problem of using DbContext as a dependancy.
What's the "protocol" in DI for calling the dbContext in singleton services?
I could use a using
statement to make sure its disposed, but then I'd have to pass the DbContextOptions using DI instead. Is this the only way to achieve this?