[英].NET Core IServiceScopeFactory.CreateScope() vs IServiceProvider.CreateScope() extension
[英]Is calling IServiceProvider.CreateScope from within a Hosted Service an anti-pattern?
最近我一直在看下面的 StackOverflow 問題。
那里有一個答案,建議閱讀 Microsoft 的文檔,尤其是在后台任務中使用范圍服務的段落。
在頁面中,我們有以下代碼的一部分:
internal class ConsumeScopedServiceHostedService : IHostedService
{
...
private void DoWork()
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is working.");
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();
scopedProcessingService.DoWork();
}
}
...
}
這不是一種反模式嗎? 在方法中創建 scope 並從服務提供者解析服務? 這似乎有一種服務定位器(如果我錯了,請糾正我)。
在 IHostedService 中沒有這樣的內置機制來獲取 Context 和 context.HttpContext.RequestServices 我認為這不是反模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.