@@ -10,10 +10,50 @@ grand_parent: My Docs
10
10
---
11
11
12
12
``` csharp
13
- using Microsoft .
14
- public static class HealthCheckExtensions
13
+ using Microsoft .Extensions .Diagnostics .HealthChecks ;
14
+
15
+ namespace Microsoft .Extensions .DependencyInjection
15
16
{
16
- public static HealthCheckService
17
+ public class SampleDatabaseHealthCheck : IHealthCheck
18
+ {
19
+ private readonly DBContext dbContext ;
20
+
21
+ public SampleDatabaseHealthCheck (DBContext dbContext )
22
+ {
23
+ this .dbContext = dbContext ;
24
+ }
25
+ public async Task <HealthCheckResult > CheckHealthAsync (HealthCheckContext context , CancellationToken cancellationToken = default )
26
+ {
27
+ try
28
+ {
29
+ // select 1 is the fastest way to detect whether the DB can be connected or not.
30
+ var result = await dbContext .ExecuteSqlCommandAsync (" Select 1" , cancellationToken );
31
+ return HealthCheckResult .Healthy ();
32
+ }
33
+ catch (System .Exception e )
34
+ {
35
+ return HealthCheckResult .Unhealthy (exception : e );
36
+ }
37
+ }
38
+ }
39
+
40
+ public static class HealthCheckExtensions
41
+ {
42
+ public static HealthCheckService GetHealthCheckService (DBContext dbContext )
43
+ {
44
+ var serviceCollection = new ServiceCollection ();
45
+ serviceCollection
46
+ .AddLogging () // HealthCheckService needs ILogger
47
+ .AddHealthChecks ()
48
+ // if the ctor needs custom arguements
49
+ .AddTypeActivatedCheck <SampleDatabaseHealthCheck >(" database" , dbContext )
50
+ // if ctor argument can be resolved by this this serviceCollection
51
+ .AddCheck <SampleDatabaseHealthCheck >(" database" );
52
+ // ensure the health check can be resolved with all the required dependecies else this throws DI error.
53
+ var serviceProvider = serviceCollection .BuildServiceProvider ();
54
+ return serviceProvider .GetRequiredService <HealthCheckService >();
55
+ }
56
+ }
17
57
}
18
58
```
19
59
0 commit comments