Last active
June 16, 2019 20:58
-
-
Save a-patel/aa5f85c55378dfedea2b9dc628ebab16 to your computer and use it in GitHub Desktop.
Health Check in ASP.NET Core (Sql Server)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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