In ASP.NET Core 10, what does AddDbContextCheck<ParkingDbContext>() run against the database, and how do you customise its query and bound its duration?
answer
- EntityFrameworkCore health check package
- Database.CanConnectAsync by default
- customTestQuery: (db, ct) => Task<bool>
- a throwing query is always Unhealthy
- no timeout parameter on the call
basics
~20 sAddDbContextCheck<TContext>() resolves the DbContext in the check's scope and calls Database.CanConnectAsync. A customTestQuery replaces that query; false yields the failureStatus, but an exception is always Unhealthy. Bound it with the registration's Timeout or a cancellable query.
solid answer
~40 s`AddDbContextCheck<ParkingDbContext>()` comes from the `Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore` package and assumes the context is already registered. It adds a check named after the type, `ParkingDbContext`, that resolves the context from the check's own scope and runs `Database.CanConnectAsync(cancellationToken)`. `true` is `Healthy`; `false` is the registration's `failureStatus`. Passing `customTestQuery: (db, ct) => db.Bays.AnyAsync(ct)` swaps in a real query that also proves the schema and permissions. One trap: the check catches exceptions itself and returns `Unhealthy`, so `failureStatus: HealthStatus.Degraded` only softens a `false` result, not a thrown one. The method has no timeout parameter; I set `Timeout` on the registration through `Configure<HealthCheckServiceOptions>`, and the query must honour the token for that to work.
code
csharp · 11 linesusing Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
builder.Services.AddHealthChecks()
.AddDbContextCheck<ParkingDbContext>(
tags: ["ready"],
customTestQuery: (db, ct) => db.Bays.AnyAsync(ct));
// No timeout parameter on AddDbContextCheck: set it on the registration.
builder.Services.Configure<HealthCheckServiceOptions>(o =>
o.Registrations.Single(r => r.Name == nameof(ParkingDbContext)).Timeout = TimeSpan.FromSeconds(2));go deeper
Know that AddDbContextCheck<TContext>() comes from the EntityFrameworkCore health check package and tests that the database can be reached.
Explain the default CanConnectAsync query, the default name, the custom query delegate, and why the context resolves safely from the check's scope.
Call out that thrown failures are always Unhealthy whatever failureStatus says, and bound the check with a registration Timeout or a cancellable query.
Weigh how deep a database readiness check should go against the load hundreds of pods put on the database at probe frequency.
## What the method registers `AddDbContextCheck<TContext>` is an extension on `IHealthChecksBuilder` from the **`Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore`** NuGet package (unlike the core health check libraries, it is not part of the ASP.NET Core shared framework). Its signature: - `AddDbContextCheck<TContext>(string? name = null, HealthStatus? failureStatus = default, IEnumerable<string>? tags = default, Func<TContext, CancellationToken, Task<bool>>? customTestQuery = default)` What it does with those arguments: 1. **Name.** If `name` is `null`, the check is named `typeof(TContext).Name`, here `ParkingDbContext`. Registering two checks for the same context therefore needs explicit names, or the duplicate-name validation fails. 2. **Custom query.** A non-null `customTestQuery` is stored in named options (`DbContextHealthCheckOptions<TContext>`) under the check's name. 3. **Registration.** It calls `AddCheck<DbContextHealthCheck<TContext>>(name, failureStatus, tags)`. The check's constructor takes `TContext` itself, so the context must be registered in DI by the app. It is resolved from the **per-check async scope** the health check service creates, so a scoped context is fine and is disposed when the check finishes. ## What runs against the database `DbContextHealthCheck<TContext>.CheckHealthAsync`: 1. picks the custom query for this registration's name, or the default `(db, ct) => db.Database.CanConnectAsync(ct)`; 2. awaits it with the check's cancellation token; 3. returns `HealthCheckResult.Healthy()` when it yields `true`; 4. returns `new HealthCheckResult(context.Registration.FailureStatus)` when it yields `false`; 5. **catches any exception** and returns `HealthCheckResult.Unhealthy(exception.Message, exception)`. The last point is the trap. Because the check catches exceptions itself, the health check service never sees them, and the registration's `FailureStatus` is never applied to them. `AddDbContextCheck<ParkingDbContext>(failureStatus: HealthStatus.Degraded)` reports `Degraded` only when the query returns `false`; a timeout exception or a failed login is still `Unhealthy`. ## Choosing the query | Query | Proves | Cost per probe | |---|---|---| | default `CanConnectAsync` | a connection can be opened | one connection from the pool | | `(db, ct) => db.Bays.AnyAsync(ct)` | the table exists and the app's login can read it | one small query | | a query over a large table | little more than the above | can be expensive at probe frequency | Keep custom queries tiny and indexed. They run on every readiness probe on every pod. ## Bounding its duration `AddDbContextCheck` has no `timeout` argument, and a registration's `Timeout` defaults to infinite, so by default the only limit is the HTTP request's own cancellation. Two ways to bound it: - **Registration timeout.** Registrations are stored in `HealthCheckServiceOptions.Registrations`. A `Configure<HealthCheckServiceOptions>` call added *after* `AddDbContextCheck` can find the registration by name and set `Timeout = TimeSpan.FromSeconds(2)`. The service then cancels the token after two seconds. - **Inside the query.** A custom query can link its own `CancellationTokenSource` with `CancelAfter`. Either way the bound is **cooperative**: it works because EF Core's async methods honour the token. When it fires, the query throws, the check's own `catch` turns that into `Unhealthy` with the exception's message, and the probe gets 503 within the bound. ## Failure modes, walked through 1. **Database stopped.** Depending on the provider and the error, the default query either returns `false`, which yields the registration's `FailureStatus`, or throws, which the check turns into `Unhealthy`. With the default `FailureStatus` both paths give `Unhealthy` and a 503 on readiness. 2. **Login revoked.** Opening the connection fails with an exception, so the entry is `Unhealthy` with the driver's message as its description. 3. **Table renamed by a bad migration.** `CanConnectAsync` still succeeds, so the default check stays `Healthy`; the custom `Bays.AnyAsync` query throws and catches it. 4. **Database slow.** Without a timeout, the readiness probe waits until the probe client gives up; with a 2-second registration timeout, the query is cancelled and the check reports `Unhealthy` promptly. ## More than one database An API that reads from a primary and a reporting replica registers two contexts with two calls, `AddDbContextCheck<ParkingDbContext>()` and `AddDbContextCheck<ReportingDbContext>()`. Their default names differ because the type names differ. Tag the replica separately if losing it should only degrade the service rather than take it out of rotation, and remember that a thrown failure is `Unhealthy` regardless. ## Where to put it Tag it for the readiness endpoint, not liveness, and keep its description out of public responses, because exception messages from database drivers can name hosts and databases.
- Why does Configure<HealthCheckServiceOptions> have to come after AddDbContextCheck?`AddDbContextCheck` ends in `IHealthChecksBuilder.Add`, which registers its own configure action that appends the registration to `HealthCheckServiceOptions.Registrations`. Configure actions run in registration order, so a later `Configure` sees the registration and can set its `Timeout`; an earlier one would find nothing and `Single` would throw.
- You register AddDbContextCheck<ParkingDbContext>() twice, once for readiness and once for a diagnostic endpoint. What happens?Both default to the name `ParkingDbContext`, and the health check service rejects duplicate names with an `ArgumentException` when it is first created. Give them distinct `name` values, or better, register the check once and select it from both endpoints with predicates.
- AddDbContextCheck runs Database.MigrateAsync to confirm the schema is current.
- failureStatus: Degraded makes every database failure report Degraded.
- AddDbContextCheck registers the DbContext for you if it is missing.
- The database check has a built-in 30-second timeout.
- A health check cannot use a scoped DbContext because checks run as singletons.