ScopedHostedService provides a clean way to implement background services with scoped dependencies in .NET.
$ dotnet add package ScopedHostedServiceA lightweight .NET library for creating hosted services with scoped dependencies.
ScopedHostedService simplifies building IHostedService implementations that need scoped services (like DbContext) without boilerplate or manual scope management.
IServiceScope for each execution, so you can safely use DbContext or other scoped services.IHostedService patterns, passing CancellationToken to your work method.IHostedService.dotnet add package ScopedHostedService
Example usage
// 1️⃣ Create a runner class
public class HelloRunner : IScopedBackgroundRunner
{
private readonly ILogger<HelloRunner> _logger;
public HelloRunner(ILogger<HelloRunner> logger)
{
_logger = logger;
}
public Task SayHelloAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Hello from ScopedHostedService!");
return Task.CompletedTask;
}
// 2️⃣ Nested hosted service
public class Service : ScopedBackgroundService<HelloRunner>
{
public override Task ExecuteInScopeAsync(HelloRunner runner, CancellationToken stoppingToken)
=> runner.SayHelloAsync(stoppingToken);
}
}
// 3️⃣ Register and run
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddLogging(config => config.AddConsole());
services.AddBackgroundServiceScoped<HelloRunner>();
})
.Build();
await host.RunAsync();