Skip to content

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.md in the ConnectSoft.BaseTemplate repository.

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
Hold "Alt" / "Option" to enable pan & zoom

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

  1. Extend BackgroundService for long-running work: override ExecuteAsync and run a loop that checks stoppingToken.IsCancellationRequested.
  2. Register via AddHostedService: Either in HostedServicesExtensions.AddMicroserviceHostedServices() or in your application startup.
  3. Use scoped services: Create a scope with IServiceProvider.CreateScope() when your hosted service needs scoped dependencies (e.g., DbContext, scoped services).
  4. 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.IsCancellationRequested in loops and complete promptly when cancellation is requested.
  • Use PeriodicTimer for timed work: For .NET 6+, PeriodicTimer is preferable to Task.Delay in loops for cleaner timed background tasks.
  • Dispose resources: Implement IDisposable or IAsyncDisposable for unmanaged resources.
  • Avoid blocking in StartAsync: The host waits for StartAsync to complete before starting the next hosted service and the server.

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.