Skip to content

Instantly share code, notes, and snippets.

@a-patel
Last active June 16, 2019 20:58
Show Gist options
  • Select an option

  • Save a-patel/aa5f85c55378dfedea2b9dc628ebab16 to your computer and use it in GitHub Desktop.

Select an option

Save a-patel/aa5f85c55378dfedea2b9dc628ebab16 to your computer and use it in GitHub Desktop.
Health Check in ASP.NET Core (Sql Server)
public class SqlServerHealthCheck : IHealthCheck
{
private readonly string _connectionString;
public SqlServerHealthCheck(string connectionString)
{
_connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
// Use dependency injection (DI) to supply any required services to the health check.
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// Execute health check logic here.
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync(cancellationToken);
using (var command = connection.CreateCommand())
{
command.CommandText = _sqlQuery;
await command.ExecuteScalarAsync();
}
return HealthCheckResult.Healthy();
}
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment