Skip to content

Commit a80e96e

Browse files
authored
Update net_standard.md
1 parent 30db8dd commit a80e96e

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

docs/dotnet_framework/net_standard.md

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,50 @@ grand_parent: My Docs
1010
---
1111

1212
``` csharp
13-
using Microsoft.
14-
public static class HealthCheckExtensions
13+
using Microsoft.Extensions.Diagnostics.HealthChecks;
14+
15+
namespace Microsoft.Extensions.DependencyInjection
1516
{
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+
}
1757
}
1858
```
1959

0 commit comments

Comments
 (0)