Best Practices¶
-
Validate early - Call
container.validate()at application startup to catch configuration errors before runtime. -
Freeze after configuration - Call
container.freeze()after all registrations to prevent accidental modifications. -
Use scopes appropriately:
SINGLETONfor expensive resources (database connections, caches)TRANSIENTfor stateful services (request handlers, commands)REQUESTfor request-scoped resources (in web applications)
-
Organize with modules - Group related dependencies into modules with clear public interfaces.
-
Prefer constructor injection - Use type-annotated constructors for dependency injection. It's the simplest and most portable approach.
-
Use interfaces - Register interfaces and bind to implementations for better testability.
-
Child containers for isolation - Use child containers for request-scoped or test-specific dependencies.
-
Use
T | Nonefor soft dependencies - Mark optional dependencies withT | Noneto avoid hard failures when a service is unavailable.