0Pricing
C# Academy · Lesson

IHostedService & BackgroundService

Implement IHostedService and the abstract BackgroundService to run work in the background within a .NET host.

What Are Background Services?

Background services run long-lived work alongside your ASP.NET Core app — processing queues, running scheduled tasks, or monitoring resources. .NET provides two interfaces: IHostedService (minimal) and the abstract BackgroundService (loop-friendly).

IHostedService Interface

IHostedService has two methods: StartAsync (called when the host starts) and StopAsync (called during graceful shutdown). Ideal for one-shot startup/shutdown tasks.

public class DatabaseMigratorService : IHostedService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public DatabaseMigratorService(IServiceScopeFactory sf) => _scopeFactory = sf;

    public async Task StartAsync(CancellationToken ct)
    {
        using var scope = _scopeFactory.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        await db.Database.MigrateAsync(ct);
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}

builder.Services.AddHostedService<DatabaseMigratorService>();

All lessons in this course

  1. IHostedService & BackgroundService
  2. Worker Service Projects
  3. Periodic Tasks & Timers
  4. Quartz.NET Scheduled Jobs
← Back to C# Academy