Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
dotnet core background hosted service with dependency injection and runs every 5 seconds
public class EmailBackgroundService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<EmailBackgroundService> _logger;
public EmailBackgroundService(IServiceProvider serviceProvider, ILogger<EmailBackgroundService> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await RunSomeprocess();
await Task.Delay(5000, stoppingToken);
}
}
private async Task RunSomeprocess()
{
using var providerScope = _serviceProvider.CreateScope();
var userService = providerScope.ServiceProvider.GetService<IUserService>();
_logger.Log( LogLevel.Information , $"{userService.GetUserId()}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment