Cette page n'est pas encore traduite. La version anglaise est affichée ci-dessous.
FDB0001: IFdbDatabase requested from dependency injection
| Analyzer | FoundationDB.Client |
| Severity | Error (fails every time at run time) |
| Code fix | Yes, when the parameter is used only for ReadAsync, WriteAsync, ReadWriteAsync, or Root |
Message
IFdbDatabase is not registered in dependency injection. Inject IFdbDatabaseProvider, which has ReadAsync, WriteAsync, ReadWriteAsync and Root.
Why
AddFoundationDb registers IFdbDatabaseProvider, not IFdbDatabase: the database connects asynchronously, so the container cannot construct it. A request for IFdbDatabase fails at run time. In a minimal API endpoint the first request returns HTTP 500 with "Body was inferred but the method does not allow inferred body parameters", because an unregistered interface parameter is read as the request body.
The rule reports:
- an
IFdbDatabaseparameter of a minimal API endpoint (MapGet,MapPost, ...); - an
IFdbDatabaseparameter marked[FromServices]; GetRequiredService<IFdbDatabase>()andGetService<IFdbDatabase>();- an
IFdbDatabaseconstructor parameter of a type registered withAddSingleton,AddScoped,AddTransient, orAddHostedService.
It reports only in a project that calls AddFoundationDb and registers no IFdbDatabase of its own. A library that takes an IFdbDatabase in a constructor is not reported.
Bad
builder.Services.AddFoundationDb(740);
var app = builder.Build();
app.MapGet("/version", async (IFdbDatabase db, CancellationToken ct) =>
{
return await db.ReadAsync(tr => tr.GetReadVersionAsync(), ct);
});
Good
builder.Services.AddFoundationDb(740);
var app = builder.Build();
app.MapGet("/version", async (IFdbDatabaseProvider db, CancellationToken ct) =>
{
return await db.ReadAsync(tr => tr.GetReadVersionAsync(), ct);
});
IFdbDatabaseProvider also has GetDatabase(ct), for code that needs the IFdbDatabase itself inside an async method.
IDE behavior
The rule needs every registration of the project before it can decide, so Visual Studio and Rider show it after a build, or with full-solution analysis turned on. dotnet build always reports it.
Suppress
When another assembly registers IFdbDatabase for this host:
#pragma warning disable FDB0001 // IFdbDatabase is registered by <assembly>
or, for a whole project, in .editorconfig:
dotnet_diagnostic.FDB0001.severity = none