Problem Statement: Develop a hosted service that runs in a dotnet core app. This service needs to support dependency injection and logging configuration from the app.
Frameworks:
Asp.Net core 3.0 (This works in 2.2 as well)
Step 1:
In Startup.cs add this hosted service to Service Collection
services.AddHostedService();
Step 2:
I just want to highlight of couple of key areas from snippet below.
- Hosted services are singleton, so you cannot inject scoped or transient services.
- Service Provider can be used to create scope from which you can get all required services from dependency container.
- Cancellation token is the key service that can be used to handle graceful shutdown and also keep the service running in the background.
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 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()}"); | |
} | |
} |
Have fun!