In modern web applications, some operations don’t need to be executed immediately within a user request. Examples include:
Sending emails or notifications
Cleaning up expired data
Generating reports
Processing queues or background jobs
ASP.NET Core provides a built-in solution for these scenarios: Hosted Services. Hosted services allow you to run background tasks independently of HTTP requests in a clean, reliable way.
This article explains how to implement background tasks using hosted services, with practical examples for full-stack applications.
What You Will Learn
What hosted services are and why they are useful
Types of hosted services in ASP.NET Core
Implementing
IHostedServicefor custom background tasksUsing
BackgroundServicefor recurring jobsScheduling tasks and cancellation handling
Best practices for production-ready background processing
Part 1: Understanding Hosted Services
A hosted service is a class that runs in the background of your ASP.NET Core application. It starts when the application starts and stops when the application shuts down.
Types:
IHostedService: Basic interface for background services.
BackgroundService: Abstract class implementing
IHostedServicewith a convenientExecuteAsyncmethod for long-running tasks.
Part 2. Creating a simple hosted service
Step 1: Create a Class Implementing BackgroundService
Services/EmailSenderService.cs
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;
public class EmailSenderService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Replace with your background logic
Console.WriteLine($"Sending emails at {DateTime.Now}");
// Wait for 1 minute before running again
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
}
Step 2: Register Hosted Service
In Program.cs:
builder.Services.AddHostedService<EmailSenderService>();
Now, when your application starts, EmailSenderService runs in the background automatically.
Part 3. Using Dependency Injection in hosted services
Hosted services can use services like DbContext, email service, or logging via dependency injection.
public class CleanupService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<CleanupService> _logger;
public CleanupService(IServiceScopeFactory scopeFactory, ILogger<CleanupService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var expiredItems = db.Tokens.Where(t => t.Expiry < DateTime.Now);
db.Tokens.RemoveRange(expiredItems);
await db.SaveChangesAsync();
_logger.LogInformation("Expired tokens cleaned at {time}", DateTime.Now);
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}
}

Join the conversation! Your thoughts help the community grow.