Search code examples
c#.net-coreasp.net-core-hosted-services

How can I troubleshoot my ASP.NET Core hosted service not working?


Problem with trying to add the Hosted Service to the Application

I'm trying to add Hosted Service to my application, but it seems not to work at all (In debug none of its methods were called). Here is the code of Hosted Service:

using Data.Data;

namespace Shop.HostedServices;

public sealed class ChangeOrderStatusHostedService : IHostedService, IDisposable
{
    private ApplicationDbContext? _db;
    private readonly IServiceScopeFactory _serviceScopeFactory;
    private Timer? _timer;

    public ChangeOrderStatusHostedService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _timer = new Timer(DoWork,
            null,
            TimeSpan.Zero,
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }
    
    private void DoWork(object? state)
    {
        using var scope = _serviceScopeFactory.CreateScope();
        _db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            
        // not important code

        _db.SaveChanges();
    }
    
    public Task StopAsync(CancellationToken stoppingToken)
    {
        _timer?.Change(Timeout.Infinite, Timeout.Infinite);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

and that's how I registered it at Program.cs

builder.Services.AddSingleton<ChangeOrderStatusHostedService>(); // here it is
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

Spent a bunch of time trying to figure this out, but the only thing I did successfully is that now my project at least builds without exceptions.


Solution

  • You have to register that hosted service via the AddHostedService extension method instead of calling builder.Services.AddSingleton<ChangeOrderStatusHostedService>().

    builder.Services.AddHostedService<ChangeOrderStatusHostedService>();
    

    Preferably and if possible inherit from BackgroundService which implements IHostedService.

    See the documentation