Skip to content

Commit

Permalink
Add DbContextChecks to Health Checks
Browse files Browse the repository at this point in the history
This will ensure that the /healthcheck endpoint correctly reports the status of the service if a database connection faults
  • Loading branch information
DrizzlyOwl committed Dec 5, 2024
1 parent 70ee728 commit f169c8f
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 62 deletions.
62 changes: 0 additions & 62 deletions TramsDataApi/Controllers/HealthCheckController.cs

This file was deleted.

2 changes: 2 additions & 0 deletions TramsDataApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,6 @@

logger.LogInformation("Logger is working...");

app.MapHealthChecks("/HealthCheck").AllowAnonymous();

app.Run();
17 changes: 17 additions & 0 deletions TramsDataApi/Setup/HealthCheckSetup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Extensions.DependencyInjection;
using TramsDataApi.DatabaseModels;

namespace TramsDataApi.Setup;

public static class HealthCheckSetup
{
public static void AddHealthChecks(IServiceCollection services) {
services.AddHealthChecks();
AddDbHealthChecks(services);
}

public static void AddDbHealthChecks(IServiceCollection services) {
services.AddHealthChecks()
.AddDbContextCheck<TramsDbContext>("Academies Database");
}
}
4 changes: 4 additions & 0 deletions TramsDataApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ namespace TramsDataApi
using TramsDataApi.ResponseModels;
using TramsDataApi.SerilogCustomEnrichers;
using TramsDataApi.Services;
using TramsDataApi.Setup;
using TramsDataApi.Swagger;
using UseCases;

Expand All @@ -53,6 +54,9 @@ public void ConfigureServices(IServiceCollection services)
services.AddDbContext<TramsDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

// Register Health Checks
HealthCheckSetup.AddHealthChecks(services);

// Add connnection to MFSP
services.AddHttpClient("MfspApiClient", (_, client) =>
{
Expand Down
1 change: 1 addition & 0 deletions TramsDataApi/TramsDataApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Microsoft.FeatureManagement.AspNetCore" Version="3.5.0" />
<PackageReference Include="NetEscapades.AspNetCore.SecurityHeaders" Version="0.22.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
Expand Down

0 comments on commit f169c8f

Please sign in to comment.