I have the some services that are multibound like this:
abstract class BaseProductService(MyDbContext db) { /* Work with the DbContext */ }
class ComputerProductService : BaseProductService {}
class CarProductService : BaseProductService {}
// Binding:
services
.AddScoped<BaseProductService, MonitorProductService>()
.AddScoped<BaseProductService, HardDriveProductService>()
.AddHostedService<ProductWorker>();
Now ProductWorker
is a BackgroundTask that supposes to grab all (not yet known) registered BaseProductService
s and execute some code:
using var scope = services.CreateScope();
var products = scope.ServiceProvider.GetServices<BaseProductService>();
// Call each product.InitAsync() in parallel
The problem is, with MyDbContext
registered to Scoped, each BaseProductService
concrete instance is sharing the same MyDbContext
instance and it's not allowed to work in parallel.
Is it:
Possible to grab the
IEnumerable<BaseProductService>
so that each instance is in its own scope?Easier to just register
MyDbContext
as Transient? Any downside I should be aware of?
Just thought of this idea: Instead of giving MyDbContext
in the constructor, maybe I can move them into InitAsync
and RunAsync
, and provide them when calling the methods instead. That way I can create one scope for each service and give them that DbContext instance.