Many .NET applications begin as simple console programs. A developer creates a console project, writes some business logic, and adds a loop to process records, check scheduled tasks, send notifications, or synchronize data.
This approach works well when the application has a limited responsibility. However, as the application grows, managing its lifecycle becomes more difficult. You may need dependency injection, structured logging, configuration management, graceful shutdown, database connections, retry handling, and support for running the application as a Windows Service or inside a container.
Instead of building all these capabilities manually, .NET provides the Generic Host and BackgroundService infrastructure.
Moving an existing console worker into a hosted background service allows you to preserve most of your business logic while using the standard .NET hosting model. This article explains how to perform that migration, organize the code, handle dependencies, and prepare the worker for production.
Understanding the Difference Between a Console Worker and a Hosted Service
A traditional console worker usually controls its own execution lifecycle. The application starts, initializes its dependencies, enters a loop, and continues running until the process is stopped.
Consider a simple console application that checks for pending jobs every minute:
while (true)
{
Console.WriteLine("Checking pending jobs...");
await ProcessPendingJobsAsync();
await Task.Delay(TimeSpan.FromMinutes(1));
}This implementation is easy to understand, but it has several limitations.
There is no standard mechanism for managing application startup and shutdown. Configuration and logging may be implemented manually. Dependencies are often created directly inside the application, making unit testing difficult. The loop also needs explicit cancellation handling to stop safely.
A hosted background service solves these problems by allowing the .NET Generic Host to manage the worker lifecycle.
The main components are:
- Generic Host: Manages application startup, shutdown, configuration, logging, and dependency injection.
- IHostedService: Defines the lifecycle methods for services managed by the host.
- BackgroundService: Provides a convenient base class for implementing long-running background operations.
- Dependency injection: Manages the creation and lifetime of application services.
- CancellationToken: Allows background operations to respond to shutdown requests.
A hosted worker does not require an ASP.NET Core application. You can use the Generic Host in a standalone worker project without adding an HTTP server.
Create a Worker Service Project
The first step is to create a Worker Service project.
You can use the .NET CLI:
dotnet new worker -n OrderProcessorMove into the project directory:
cd OrderProcessorThe Worker Service template provides a basic application structure, including Program.cs and Worker.cs.
The project uses the Worker SDK:
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>The target framework should match the .NET version used by your solution. The important point is that the Worker SDK provides the foundation for building a hosted background application.
If you already have a console project, you do not necessarily need to replace the entire project. You can introduce Generic Host into the existing application and migrate the worker logic gradually.
Separate Business Logic From the Console Loop
Before converting the application, identify the actual work performed by the console program.
For example, imagine an existing worker that processes pending orders. Its current implementation might look like this:
public class Program
{
public static async Task Main()
{
while (true)
{
Console.WriteLine("Processing orders...");
await ProcessOrdersAsync();
await Task.Delay(5000);
}
}
private static async Task ProcessOrdersAsync()
{
// Fetch and process pending orders.
await Task.CompletedTask;
}
}The problem is not necessarily the processing logic. The problem is that the business operation and execution lifecycle are combined inside Program.
Move the processing operation into a separate service:
public interface IOrderProcessor
{
Task ProcessPendingOrdersAsync(
CancellationToken cancellationToken);
}Implement the interface:
public class OrderProcessor : IOrderProcessor
{
private readonly ILogger<OrderProcessor> _logger;
public OrderProcessor(
ILogger<OrderProcessor> logger)
{
_logger = logger;
}
public async Task ProcessPendingOrdersAsync(
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Processing pending orders");
// Fetch pending orders.
// Apply business rules.
// Update order status.
await Task.CompletedTask;
}
}This separation makes the processing logic reusable. It can be called by a hosted worker, a command-line operation, or an automated test without depending on the console application's execution loop.
Implement the BackgroundService
Once the business logic is separated, create a class that inherits from BackgroundService.
public class OrderWorker : BackgroundService
{
private readonly IOrderProcessor _orderProcessor;
private readonly ILogger<OrderWorker> _logger;
public OrderWorker(
IOrderProcessor orderProcessor,
ILogger<OrderWorker> logger)
{
_orderProcessor = orderProcessor;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
_logger.LogInformation(
"Order worker started");
while (!stoppingToken.IsCancellationRequested)
{
try
{
await _orderProcessor.ProcessPendingOrdersAsync(
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An error occurred while processing orders");
}
await Task.Delay(
TimeSpan.FromSeconds(5),
stoppingToken);
}
_logger.LogInformation(
"Order worker stopped");
}
}The ExecuteAsync method contains the main background execution logic.
The stoppingToken is supplied by the host. When the application receives a shutdown request, the token is cancelled. The worker checks this token and passes it to the business service so that ongoing operations can also respond to cancellation.
The example catches unexpected processing exceptions and logs them, allowing the loop to continue. In a production system, this behavior should be intentional. Some failures should trigger retries, while others may indicate that the worker cannot safely continue.
The delay is also cancellation-aware. This prevents the worker from waiting for the full five seconds when the application is shutting down.
Configure Dependency Injection and the Host
The next step is to register the business service and background worker with the Generic Host.
Program.cs can be kept simple:
using OrderProcessor;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddScoped<IOrderProcessor, OrderProcessor>();
builder.Services.AddHostedService<OrderWorker>();
var host = builder.Build();
await host.RunAsync();The Generic Host provides configuration, logging, and dependency injection without requiring an ASP.NET Core web application.
The AddHostedService method registers the worker so that the host starts and stops it automatically.
The AddScoped registration also demonstrates an important point: a hosted service is typically registered as a singleton, while business services may use scoped lifetimes.
You should not directly inject a scoped service into a singleton hosted service. Instead, create a dependency injection scope when processing each batch.
Join the conversation! Your thoughts help the community grow.