Hosted Services in ConnectSoft Base Template¶
Purpose & Overview¶
Hosted Services in the ConnectSoft Base Template provide a standardized way to run background tasks for the lifetime of the application. They implement the ASP.NET Core IHostedService interface and enable long-running work such as startup warmup gates, data ingestion, and integration with third-party background job processors.
For Base Template-specific configuration, implementation details, and how to add custom hosted services, see the Base Template
docs/Hosted Services.mdin theConnectSoft.BaseTemplaterepository.
Hosted services provide:
- Application Lifetime Tasks: Background work that runs from startup until shutdown
- Graceful Shutdown: Cancellation token support with configurable shutdown timeout
- Dependency Injection: Full access to the DI container (use scopes for scoped services)
- Centralized Registration:
AddMicroserviceHostedServices()wires all template-managed services
Hosted Services vs Background Jobs
Hosted services run continuously for the app lifetime (e.g., warmup gates, polling). Background jobs (Hangfire, Quartz) run discrete units of work on a schedule or when enqueued. Hangfire's Background Job Server is itself an IHostedService.
Architecture Overview¶
Hosted Service Lifecycle¶
flowchart TD
subgraph Host [Application Host]
Start[Host Start] --> StartAsync[StartAsync]
StartAsync --> Execute[ExecuteAsync / DoWork]
Execute --> Running[Running]
Running --> Stop[Host Stop]
Stop --> StopAsync[StopAsync]
StopAsync --> Dispose[Dispose]
end
Base Template Integration Points¶
Application Startup
├── AddMicroserviceHostedServices()
│ ├── StartupWarmupGate (if HealthCheck)
│ └── VectorIngestionHost (if UseVectorIngestionHost)
├── AddMicroserviceHangFire() → Background Job Server (IHostedService)
├── MassTransit → Bus HostedService
└── Custom AddHostedService<T>()
↓
Host Lifecycle
├── StartAsync → Background work begins
├── ExecuteAsync / DoWork runs until cancellation
└── StopAsync → Graceful shutdown
Template-Managed Services¶
StartupWarmupGate¶
Purpose: Provides a configurable grace period after startup before the instance is considered ready. Health checks that depend on slow-starting subsystems (e.g., SignalR, database migrations) can use IStartupWarmupGate.IsReady to avoid reporting healthy prematurely.
When registered: When the HealthCheck template flag is enabled.
Configuration: BaseTemplate:StartupWarmupSeconds (default: 20). Set to 0 to disable the grace window in tests.
VectorIngestionHost¶
Purpose: A BackgroundService that periodically ingests sample data into the vector store for RAG and semantic search scenarios. Uses Microsoft's IngestionPipeline and keyed services from ConnectSoft.Extensions.AI.
When registered: When the UseVectorIngestionHost template flag is enabled.
See Vector Ingestion for details.
Adding Custom Hosted Services¶
- Extend BackgroundService for long-running work: override
ExecuteAsyncand run a loop that checksstoppingToken.IsCancellationRequested. - Register via AddHostedService: Either in
HostedServicesExtensions.AddMicroserviceHostedServices()or in your application startup. - Use scoped services: Create a scope with
IServiceProvider.CreateScope()when your hosted service needs scoped dependencies (e.g., DbContext, scoped services). - Keep StartAsync short: Hosted services are started sequentially; avoid long-running initialization in
StartAsync.
For code examples and best practices, see the Base Template docs/Hosted Services.md in the ConnectSoft.BaseTemplate repository.
Best Practices¶
- Respond to cancellation: Check
stoppingToken.IsCancellationRequestedin loops and complete promptly when cancellation is requested. - Use PeriodicTimer for timed work: For .NET 6+,
PeriodicTimeris preferable toTask.Delayin loops for cleaner timed background tasks. - Dispose resources: Implement
IDisposableorIAsyncDisposablefor unmanaged resources. - Avoid blocking in StartAsync: The host waits for
StartAsyncto complete before starting the next hosted service and the server.
Related Documentation¶
- Application Model: Hosted service registration pattern
- Hosting: Application host and lifecycle
- Hangfire: Background jobs (Hangfire uses IHostedService for its job server)
- Health Checks: Integration with StartupWarmupGate
Summary¶
Hosted services in the ConnectSoft Base Template enable reliable, lifecycle-aware background work. The template centralizes registration in AddMicroserviceHostedServices(), provides StartupWarmupGate for health check coordination, and VectorIngestionHost for AI data ingestion. Custom hosted services follow the standard ASP.NET Core patterns with full DI support.