Lifecycle — Aquilia Documentation
Comprehensive guide and documentation for Lifecycle in the Aquilia framework. View API reference, examples, and implementation patterns.
Dependency Injection / Lifecycle Lifecycle Hooks & Disposal The lifecycle engine under aquilia/di/lifecycle.py manages priority-ordered startup transitions, LIFO finalization hooks, and disposal strategies. DisposalStrategy Governs the execution behavior of registered finalizers during container teardown: from aquilia.di import DisposalStrategy class DisposalStrategy(str, Enum): LIFO = "lifo" # Last-in, first-out (default) FIFO = "fifo" # First-in, first-out PARALLEL = "parallel" # Concurrent teardown via asyncio.gather Strategy Order Use Case ))} LifecycleHook Dataclass wrapping startup or teardown callbacks: from dataclasses import dataclass from typing import Callable @dataclass class LifecycleHook: name: str # Hook identifier callback: Callable # Async callable to execute priority: int = 0 # Higher priority runs FIRST phase: str = "shutdown" # "startup" or "shutdown" Register hooks manually with on_startup / on_shutdown (both take name and priority keyword args), and cleanup callbacks with register_finalizer: lifecycle = Lifecycle( disposal_strategy=DisposalStrategy.LIFO, hook_timeout=30.0, # per-hook timeout in seconds ) lifecycle.on_startup(connect_db, name="db.connect", priority=100) # runs first lifecycle.on_startup(warm_cache, name="cache.warm", priority=10) lifecycle.on_shutdown(flush_metrics, name="metrics.flush") lifecycle.register_finalizer(close_sockets) Hook Execution Semantics . ))} Auto-Detection of Lifecycle Methods The container scans registered services automatically. If a class exposes on_startup or on_shutdown, it is bound as a lifecycle hook: @service(scope="singleton") class DatabasePool: def __init__(self, config: AppConfig): self.config = config self.pool = None async def on_startup(self): """Discovered automatically: registered as a startup hook.""" self.pool = await asyncpg.create_pool(dsn=self.config.db_url) async def on_shutdown(self): """Discovered automatically: registered as a shutdown hook.""" if self.pool: await self.pool.close() Request vs App Lifecycle Aspect App Container Request Container ))} Full Lifecycle Context from aquilia.di import LifecycleContext # Build and run the app server inside a LifecycleContext container = registry.build_container() async with LifecycleContext(container): # 1. Triggers container.startup() # 2. Runs all startup hooks await run_server() # 3. Triggers container.shutdown() on block exit # 4. Cleans finalizers LIFO → shutdown hooks priority Decorators Diagnostics )
Go to Homepage