C#C
C#3y ago
TeBeCo

✅ [ASPNETCORE - HealthCheck - Timeout] Trying to find a more elegant way to write this

ok soooo question about HealthCheck:
I'm trying to configure the Timeout through IOptions<> which is bound to my configuration
  • of course reading IConfiguration.GetValue<> is a NO GO here
  • added code for "lol harcode / not configurable" way
  • added code for equivalent which uses configuration binding through options
Am I missing a better way ?

public class Foo : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
        => await Task.Delay(2000, ct);  return HealthCheckResult.Healthy("");
}
public class FooOptions
{
    public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(1);
}

/////////
// I hate it because it's not configurable at startup time:
// builder.Services.AddHealthChecks()
//                .AddCheck<Foo>("foo", null, null, TimeSpan.FromSeconds(1));
/////////


// Workaround:
builder.Services.AddHealthChecks()
                .AddCheck<Foo>("foo");
builder.Services.AddOptions<HealthCheckServiceOptions>()
                .PostConfigure<IOptions<FooOptions>>((options, myOptions) =>
                {
                    var registrations = options.Registrations.Where(registration => registration.Name == "foo");
                    foreach (var registration in registrations)
                    {
                        registration.Timeout = myOptions.Value.Timeout;
                    }
                });
Was this page helpful?