CG.Infrastructure.Health 3.10.8

dotnet add package CG.Infrastructure.Health --version 3.10.8
                    
NuGet\Install-Package CG.Infrastructure.Health -Version 3.10.8
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CG.Infrastructure.Health" Version="3.10.8" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CG.Infrastructure.Health" Version="3.10.8" />
                    
Directory.Packages.props
<PackageReference Include="CG.Infrastructure.Health" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CG.Infrastructure.Health --version 3.10.8
                    
#r "nuget: CG.Infrastructure.Health, 3.10.8"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CG.Infrastructure.Health@3.10.8
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CG.Infrastructure.Health&version=3.10.8
                    
Install as a Cake Addin
#tool nuget:?package=CG.Infrastructure.Health&version=3.10.8
                    
Install as a Cake Tool

CG.Infrastructure.Health

A comprehensive health monitoring library for .NET applications that provides robust health checks for databases, APIs, and identity services with configurable options and detailed reporting.

Features

  • Database Health Checks: SQL Server connectivity monitoring with connection pooling support
  • API Health Checks: External API endpoint monitoring with configurable timeouts
  • Identity Server Health Checks: Authentication service availability monitoring
  • Configurable Health Check Options: Timeout, retry count, and logging configuration
  • Docker Support: Automatic endpoint selection for containerized environments
  • Comprehensive Reporting: Detailed health status with connection information
  • Dependency Injection Ready: Easy integration with ASP.NET Core applications

Installation

dotnet add package CG.Infrastructure.Health

Quick Start

1. Register Services

using Infrastructure.Health.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Register health check services
builder.Services.RegisterInfraHealthCheckServices(builder.Configuration);

2. Configure Health Check Endpoint

var app = builder.Build();

// Map health check endpoint
app.MapHealthChecks("/health");

3. Add Configuration

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=MyDb;Trusted_Connection=true;",
    "ReadOnlyConnection": "Server=localhost;Database=MyDbReadOnly;Trusted_Connection=true;"
  },
  "ApiOptions": {
    "UseDocker": false,
    "UserApiClients": ["https://api.users.com", "https://api.users-backup.com"],
    "OrderApiClients": ["https://api.orders.com"]
  },
  "IssuerOptions": {
    "Authority": "https://identity.example.com",
    "Audience": "my-api"
  },
  "HealthCheckOptions": {
    "TimeoutSeconds": 30,
    "RetryCount": 3,
    "RetryDelay": "00:00:05",
    "EnableDetailedLogging": true,
    "CheckDiscoveryEndpoint": true
  }
}

Core Services

IHealthCheckService

Core interface for health check operations:

public interface IHealthCheckService : IService
{
    Task<HealthReport> CheckHealthAsync(CancellationToken cancellationToken = default);
}

IHealthReportService

Service for generating health reports in various formats:

public interface IHealthReportService : IService
{
    Task<HealthReport> GetHealthReportAsync(CancellationToken cancellationToken = default);
    Task<string> GetHealthReportJsonAsync(CancellationToken cancellationToken = default);
}

Health Checks

SQL Server Health Check

Monitors database connectivity with configurable retry logic and detailed connection information.

Features:

  • Connection pooling support
  • Configurable timeout and retry settings
  • Detailed connection metadata (server, database, retry count)
  • Aggregate health status across multiple connections

Configuration:

{
  "ConnectionStrings": {
    "PrimaryDb": "Server=localhost;Database=PrimaryDb;Trusted_Connection=true;",
    "SecondaryDb": "Server=localhost;Database=SecondaryDb;Trusted_Connection=true;"
  }
}

API Health Check

Monitors external API endpoints with intelligent endpoint selection.

Features:

  • Docker-aware endpoint selection
  • Multiple endpoint fallback support
  • Configurable timeout settings
  • Health status aggregation

Configuration:

{
  "ApiOptions": {
    "UseDocker": true,
    "UserApiClients": ["http://user-api:8080", "https://user-api.example.com"],
    "OrderApiClients": ["http://order-api:8080", "https://order-api.example.com"]
  }
}

Identity Server Health Check

Monitors authentication service availability and discovery endpoint health.

Features:

  • Discovery endpoint validation
  • Authority endpoint monitoring
  • Configurable audience validation
  • Detailed authentication service status

Configuration:

{
  "IssuerOptions": {
    "Authority": "https://identity.example.com",
    "Audience": "my-api"
  }
}

Configuration Options

HealthCheckOptions

public class HealthCheckOptions
{
    public int TimeoutSeconds { get; set; } = 30;           // Health check timeout
    public int RetryCount { get; set; } = 3;                // Number of retry attempts
    public TimeSpan RetryDelay { get; set; } = TimeSpan.FromSeconds(5);  // Delay between retries
    public bool EnableDetailedLogging { get; set; } = false; // Enable verbose logging
    public bool CheckDiscoveryEndpoint { get; set; } = true; // Validate discovery endpoints
}

ApiEndpointOptions

public class ApiEndpointOptions
{
    public bool UseDocker { get; set; } = false;            // Use Docker endpoint selection
    public List<string> ApiClients { get; set; } = [];      // API endpoint URLs
}

Advanced Usage

Custom Health Check Registration

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services, IConfiguration configuration)
    {
        services.RegisterInfraHealthCheckServices(configuration);
        
        // Add custom health checks
        services.AddHealthChecks()
            .AddCheck<CustomHealthCheck>("custom", tags: ["custom"]);
            
        return services;
    }
}

Health Check Filtering

app.MapHealthChecks("/health", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("database"),
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

Custom Health Check Implementation

public class CustomHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
        try
        {
            // Custom health check logic
            return Task.FromResult(HealthCheckResult.Healthy("Custom check passed"));
        }
        catch (Exception ex)
        {
            return Task.FromResult(HealthCheckResult.Unhealthy("Custom check failed", ex));
        }
    }
}

Health Check Response Format

Healthy Response

{
  "status": "Healthy",
  "totalDuration": "00:00:00.1234567",
  "entries": {
    "sql-server": {
      "data": {
        "healthyConnections": ["PrimaryDb", "SecondaryDb"],
        "server": "localhost",
        "database": "PrimaryDb"
      },
      "duration": "00:00:00.0456789",
      "status": "Healthy",
      "tags": ["database", "sql"]
    }
  }
}

Unhealthy Response

{
  "status": "Unhealthy",
  "totalDuration": "00:00:00.2345678",
  "entries": {
    "sql-server": {
      "data": {
        "unhealthyConnections": ["PrimaryDb"],
        "healthyConnections": ["SecondaryDb"]
      },
      "duration": "00:00:00.1234567",
      "status": "Unhealthy",
      "description": "Database connections unhealthy: 'PrimaryDb'",
      "tags": ["database", "sql"]
    }
  }
}

Dependencies

  • CG.Infrastructure.Configuration (3.10.1) - Configuration management
  • CG.Infrastructure.Core (3.10.7) - Core infrastructure services
  • CG.Infrastructure.Services (3.10.2) - Shared service implementations
  • Microsoft.Data.SqlClient (6.0.2) - SQL Server connectivity
  • Microsoft.Extensions.Diagnostics.HealthChecks (9.0.8) - Health check framework
  • Microsoft.Extensions.Http (9.0.8) - HTTP client factory
  • Microsoft.Extensions.Logging (9.0.8) - Logging infrastructure

Best Practices

  1. Configuration Management: Use strongly-typed configuration options for health check settings
  2. Endpoint Selection: Configure multiple endpoints for high availability scenarios
  3. Timeout Configuration: Set appropriate timeouts based on your infrastructure requirements
  4. Retry Logic: Use retry mechanisms for transient failures
  5. Logging: Enable detailed logging for debugging health check issues
  6. Docker Support: Use Docker-aware endpoint selection in containerized environments

Monitoring and Alerting

Health Check Endpoints

  • Overall Health: /health - Complete health status
  • Database Health: /health?tags=database - Database-specific health
  • API Health: /health?tags=api - API endpoint health
  • Identity Health: /health?tags=identity - Identity service health

Integration with Monitoring Systems

The library integrates seamlessly with:

  • Azure Application Insights
  • Prometheus (via health check metrics)
  • Grafana dashboards
  • Custom monitoring solutions

Troubleshooting

Common Issues

  1. Connection Timeouts: Increase TimeoutSeconds in configuration
  2. Retry Failures: Adjust RetryCount and RetryDelay settings
  3. Endpoint Selection: Verify UseDocker setting matches your environment
  4. Configuration Loading: Ensure configuration sections are properly structured

Debug Mode

Enable detailed logging for troubleshooting:

{
  "HealthCheckOptions": {
    "EnableDetailedLogging": true
  }
}

Version History

  • 3.10.3: Current release with comprehensive health monitoring
  • 3.10.2: Enhanced API health check functionality
  • 3.10.1: Initial health check framework
  • 3.10.0: Foundation release

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For support and questions:

  • Create an issue in the repository
  • Check the documentation
  • Review the test examples

CG.Infrastructure.Health - Robust health monitoring for modern .NET applications.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.10.8 123 8/21/2025
3.10.7 121 8/21/2025
3.10.6 58 8/16/2025
3.10.5 101 8/15/2025
3.10.4 128 8/10/2025
3.10.3 452 7/21/2025
3.10.2 30 7/19/2025
3.10.1 71 7/18/2025
3.10.0 74 7/18/2025
3.9.0 136 12/10/2024
3.0.0 168 8/19/2024
1.0.0 286 5/27/2022