Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading