Skip to content

Commit

Permalink
Update net_standard.md
Browse files Browse the repository at this point in the history
  • Loading branch information
sj-net authored Sep 27, 2024
1 parent 30db8dd commit a80e96e
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions docs/dotnet_framework/net_standard.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,50 @@ grand_parent: My Docs
---

``` csharp
using Microsoft.
public static class HealthCheckExtensions
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Microsoft.Extensions.DependencyInjection
{
public static HealthCheckService
public class SampleDatabaseHealthCheck : IHealthCheck
{
private readonly DBContext dbContext;

public SampleDatabaseHealthCheck(DBContext dbContext)
{
this.dbContext = dbContext;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// select 1 is the fastest way to detect whether the DB can be connected or not.
var result = await dbContext.ExecuteSqlCommandAsync("Select 1", cancellationToken);
return HealthCheckResult.Healthy();
}
catch (System.Exception e)
{
return HealthCheckResult.Unhealthy(exception: e);
}
}
}

public static class HealthCheckExtensions
{
public static HealthCheckService GetHealthCheckService(DBContext dbContext)
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddLogging() // HealthCheckService needs ILogger
.AddHealthChecks()
// if the ctor needs custom arguements
.AddTypeActivatedCheck<SampleDatabaseHealthCheck>("database", dbContext)
// if ctor argument can be resolved by this this serviceCollection
.AddCheck<SampleDatabaseHealthCheck>("database");
// ensure the health check can be resolved with all the required dependecies else this throws DI error.
var serviceProvider = serviceCollection.BuildServiceProvider();
return serviceProvider.GetRequiredService<HealthCheckService>();
}
}
}
```

Expand Down

0 comments on commit a80e96e

Please sign in to comment.