-
Notifications
You must be signed in to change notification settings - Fork 815
/
Copy pathSqliteHealthCheck.cs
43 lines (36 loc) · 1.47 KB
/
SqliteHealthCheck.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace HealthChecks.Sqlite;
/// <summary>
/// A health check for Sqlite services.
/// </summary>
public class SqliteHealthCheck : IHealthCheck
{
private readonly SqliteHealthCheckOptions _options;
public SqliteHealthCheck(SqliteHealthCheckOptions options)
{
Guard.ThrowIfNull(options.ConnectionString, true);
Guard.ThrowIfNull(options.CommandText, true);
_options = options;
}
/// <inheritdoc />
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
using var connection = new SqliteConnection(_options.ConnectionString);
_options.Configure?.Invoke(connection);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
using var command = connection.CreateCommand();
command.CommandText = _options.CommandText;
object? result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
return _options.HealthCheckResultBuilder == null
? HealthCheckResult.Healthy()
: _options.HealthCheckResultBuilder(result);
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}