ASP.NET Core Interview Question #163

How do you register a hosted service?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

Hosted services are normally registered with AddHostedService<T>(). The host creates and manages the service as part of application startup and shutdown.

Detailed Explanation

Hosted services are normally registered with AddHostedService<T>(). The host creates and manages the service as part of application startup and shutdown.

A hosted service is effectively long-lived, so it should not directly capture scoped dependencies such as an EF Core DbContext in its constructor.

When scoped work is needed, inject IServiceScopeFactory and create a scope for each logical operation.

Code Example

builder.Services.AddHostedService<QueueWorker>();

var app = builder.Build();
app.Run();