When trying to resolve a scoped dependency inside a HostedService, the runtime returned the following error message:
System.InvalidOperationException: Cannot consume scoped service āIScopedā from singleton āMicrosoft.Extensions.Hosting.IHostedServiceā.
The problem is that the IHostedService is a singleton and is created outside a dependency injection scope. Trying to inject any scoped service(e.g. an EF Core DbContext) will result in the error message above.
To solve this problem you have to create a dependency injection scope using the IServiceScopeFactory. Within this scope you can use the scoped services:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Worker : BackgroundService | |
{ | |
private readonly ILogger<Worker> _logger; | |
private readonly IServiceScopeFactory _serviceScopeFactory; | |
public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory) | |
{ | |
_logger = logger; | |
_serviceScopeFactory = serviceScopeFactory; | |
} | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
using (var scope = _serviceScopeFactory.CreateScope()) | |
{ | |
var dbContext = scope.ServiceProvider.GetRequiredService<ExampleDbContext>(); | |
//Do something here | |
} | |
} | |
} | |
} |