Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Common/src/Common/HealthChecks/HealthAggregator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Concurrent;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Steeltoe.Common.Extensions;
using MicrosoftHealthCheckResult = Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult;
Expand Down Expand Up @@ -108,7 +109,10 @@ private static async Task<SteeltoeHealthCheckResult> RunMicrosoftHealthCheckAsyn

try
{
IHealthCheck check = registration.Factory(serviceProvider);
// Match the behavior of ASP.NET's HealthCheckService, which creates a scope for each check.
await using AsyncServiceScope serviceScope = serviceProvider.CreateAsyncScope();

IHealthCheck check = registration.Factory(serviceScope.ServiceProvider);
MicrosoftHealthCheckResult result = await check.CheckHealthAsync(context, cancellationToken);

healthCheckResult.Status = ToHealthStatus(result.Status);
Expand Down
1 change: 1 addition & 0 deletions src/Common/test/TestResources/TestHostBuilderFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ private static void ConfigureBuilder(HostBuilder builder, bool configureWebHost,
{
builder.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder.UseDefaultServiceProvider(ConfigureServiceProvider);
webHostBuilder.Configure(EmptyAction);

if (useTestServer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;

namespace Steeltoe.Common.TestResources;

Expand Down Expand Up @@ -89,6 +90,7 @@ public static WebApplicationBuilder CreateDefault(bool useTestServer)

private static void ConfigureBuilder(WebApplicationBuilder builder, bool useTestServer, bool deactivateDiagnostics)
{
builder.Host.UseDefaultServiceProvider(ConfigureServiceProvider);
builder.WebHost.UseDefaultServiceProvider(ConfigureServiceProvider);

if (useTestServer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private static void RegisterDefaultHealthContributors(IServiceCollection service
}

/// <summary>
/// Adds the specified <see cref="IHealthContributor" /> to the D/I container as a scoped service.
/// Adds the specified <see cref="IHealthContributor" /> to the D/I container as a singleton service.
/// </summary>
/// <typeparam name="T">
/// The type of health contributor to add.
Expand All @@ -98,7 +98,7 @@ public static IServiceCollection AddHealthContributor<T>(this IServiceCollection
}

/// <summary>
/// Adds the specified <see cref="IHealthContributor" /> to the D/I container as a scoped service.
/// Adds the specified <see cref="IHealthContributor" /> to the D/I container as a singleton service.
/// </summary>
/// <param name="services">
/// The <see cref="IServiceCollection" /> to add services to.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using FluentAssertions.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
Expand Down Expand Up @@ -516,6 +517,50 @@ public async Task Converts_AspNet_health_check_results()
""");
}

[Fact]
public async Task Can_use_scoped_AspNet_health_check()
{
WebApplicationBuilder builder = TestWebApplicationBuilderFactory.Create();
builder.Configuration.AddInMemoryCollection(AppSettings);
builder.Services.AddDbContext<TestDbContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
builder.Services.AddHealthChecks().AddDbContextCheck<TestDbContext>();
builder.Services.AddHealthActuator();
await using WebApplication host = builder.Build();

// ReSharper disable once AccessToDisposedClosure
Action action = () => host.Services.GetRequiredService<TestDbContext>();
action.Should().ThrowExactly<InvalidOperationException>();

host.MapHealthChecks("/health");
await host.StartAsync(TestContext.Current.CancellationToken);
using HttpClient httpClient = host.GetTestClient();

HttpResponseMessage actuatorResponse = await httpClient.GetAsync(new Uri("http://localhost/actuator/health"), TestContext.Current.CancellationToken);

actuatorResponse.StatusCode.Should().Be(HttpStatusCode.OK);

string actuatorResponseBody = await actuatorResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);

actuatorResponseBody.Should().BeJson("""
{
"status": "UP",
"components": {
"TestDbContext": {
"status": "UP"
}
}
}
""");

HttpResponseMessage aspNetResponse = await httpClient.GetAsync(new Uri("http://localhost/health"), TestContext.Current.CancellationToken);

aspNetResponse.StatusCode.Should().Be(HttpStatusCode.OK);

string aspNetResponseBody = await aspNetResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);

aspNetResponseBody.Should().Be("Healthy");
}

private sealed class AspNetHealthyCheck : IHealthCheck
{
public async Task<MicrosoftHealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
Expand Down Expand Up @@ -562,4 +607,7 @@ public Task<MicrosoftHealthCheckResult> CheckHealthAsync(HealthCheckContext cont
throw new InvalidOperationException("test-exception");
}
}

private sealed class TestDbContext(DbContextOptions options)
: DbContext(options);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="$(MatchTargetFrameworkVersion)" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="$(EntityFrameworkCoreTestVersion)" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="$(EntityFrameworkCoreTestVersion)" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="$(EntityFrameworkCoreTestVersion)" />
</ItemGroup>

<ItemGroup>
Expand Down