最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

.net - Is there a way to get C# multi-bound services (ServiceProvider.GetServices<T>) but each instance in their o

programmeradmin5浏览0评论

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 BaseProductServices 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论