Last active
September 17, 2024 02:46
-
-
Save poojarsn/f319427e571163f8e1313004950001d4 to your computer and use it in GitHub Desktop.
How to inject a scoped service into a singleton service?
This file contains hidden or 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 SomeSingletonService(IServiceScopeFactory serviceScopeFactory) | |
: SingletonService | |
{ | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
using IServiceScope scope = serviceScopeFactory.CreateScope(); | |
var dbContext = scope | |
.ServiceProvider | |
.GetRequiredService<ApplicationDbContext>(); | |
// Do some background processing with the EF database context. | |
await DoWorkAsync(dbContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment