Recently I have been looking at the following StackOverflow question.
There is an answer there suggesting a read at Microsoft's documentation and especially the paragraph Consuming a scoped service in a background task.
In the page there we have parts of the following code:
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();
}
}
...
}
Isn't this a kind of an anti-pattern? To create a scope inside a method and resolve a service from the service provider? This seems like having a kind of a Service locator (correct me if I am wrong).