Dotnet Core Hosted Service

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.
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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s