CLI frameworks like Typer or Click inspect function signatures to generate command-line options. If you use @injectable on a CLI command, the injected dependencies will incorrectly appear as CLI options.
To avoid this, do not use the @injectable decorator on CLI commands. Instead, resolve dependencies manually inside the function body using get_injected_obj(dependency_function).
Important: Since CLI commands are often short-lived processes, ensure you clean up resources (like database connections or caches) before the process exits using run_coroutine_sync(cleanup_all_exit_stacks()) and run_coroutine_sync(clear_dependency_cache()).
import typer
from fastapi_injectable import (
cleanup_all_exit_stacks,
clear_dependency_cache,
get_injected_obj,
run_coroutine_sync,
)
cli = typer.Typer()
@cli.command()
def migrate(target: str) -> None:
# Resolve inside the body to prevent leaking into CLI options
db: DbSession = get_injected_obj(get_db)
typer.echo(f"migrating to {target} (connected={db.connected})")
# Clean up before the process exits
run_coroutine_sync(cleanup_all_exit_stacks())
run_coroutine_sync(clear_dependency_cache())
if __name__ == "__main__":
cli()