Skip to content

blackbull.di

blackbull.di

Per-request dependency injection for simplified handlers.

Depends marks a simplified-handler parameter as provided by the framework rather than by the request::

async def get_db():                    # async-generator provider
    pool = await create_pool()
    try:
        yield pool                     # ← injected value
    finally:
        await pool.close()             # ← runs after the response is sent

@app.route(path='/items/{id:int}')
async def get_item(id: int, db=Depends(get_db)):
    return await db.fetch_item(id)

Design (Sprint 74): everything is resolved at registration time on the _adapt_handler seam — a handler that declares no Depends parameter compiles to exactly the wrapper it compiled to before this module existed (no per-request stack, no empty dependency loop). Contrast FastAPI, which enters two AsyncExitStacks and runs solve_dependencies() on every request even with an empty dependency list.

v1 scope fences (add on real demand, not speculatively):

  • providers take no parameters — a provider that itself declares Depends (nesting) is a registration-time TypeError;
  • simplified handlers only — middleware and full (scope, receive, send) handlers are unchanged;
  • no interface binding and no interception: duck typing and the event API (@app.intercept) already cover those.

Depends

Declare a per-request provider for one simplified-handler parameter.

Use as the parameter's default value: db=Depends(get_db).

Provider forms (detected once, here):

  • async generator — yields the injected value exactly once; the code after yield (or the finally block) runs after the response has been sent, LIFO when several providers are active.
  • async function — awaited for the value; no cleanup.
  • sync function — called for the value; no cleanup.

Parameters:

Name Type Description Default
provider Callable[[], Any]

Zero-parameter callable in one of the three forms above.

required
use_cache bool

When True (default), parameters of one handler that name the same provider share a single instance per request; use_cache=False calls the provider once per parameter.

True

Raises:

Type Description
TypeError

At construction, when provider is not callable, takes parameters (including a nested Depends default — not supported in v1), or is a sync generator function.