Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton

Update

In the past, a HostedService was a long-lived transient, effectively acting as a singleton. Since .NET Core 3.1 it’s an actual Singleton.


Use AddHostedService

A hosted service is more than just a singleton service. The runtime “knows” about it, can tell it to start by calling StartAsync or stop by calling StopAsync() whenever eg the application pool is recycled. The runtime can wait for the hosted service to finish before the web application itself terminates.

As the documentation explains a scoped service can be consumed by creating a scope inside the hosted service’s worker method. The same holds for transient services.

To do so, an IServicesProvider or an IServiceScopeFactory has to be injected in the hosted service’s constructor and used to create the scope.

Borrowing from the docs, the service’s constructor and worker method can look like this:

public IServiceProvider Services { get; }

public ConsumeScopedServiceHostedService(IServiceProvider services, 
    ILogger<ConsumeScopedServiceHostedService> logger)
{
    Services = services;
    _logger = logger;
}


private void DoWork()
{
    using (var scope = Services.CreateScope())
    {
        var scopedProcessingService = 
            scope.ServiceProvider
                .GetRequiredService<IScopedProcessingService>();

        scopedProcessingService.DoWork();
    }
}

This related question shows how to use a transient DbContext in a hosted service:

public class MyHostedService : IHostedService
{
    private readonly IServiceScopeFactory scopeFactory;

    public MyHostedService(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    public void DoWork()
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
            …
        }
    }
    …
}

Leave a Comment