Inject is a lightweight, fast, and thread-safe Python dependency injection framework. It facilitates the creation and management of object dependencies, promoting modular and testable code. The library supports features like automatic parameter injection using type annotations and context managers. It maintains an active development status, with the current version being 5.3.0, and new releases are made periodically.
pip install injectVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up and use `inject` for dependency injection. It covers configuring bindings, requesting instances directly with `inject.instance()`, and automatically injecting parameters into functions using `@inject.autoparams` (with type hints) or explicitly with `@inject.params`.
Upgrade your Python environment to 3.9+ or pin `inject` to an appropriate older major version (e.g., `pip install 'inject<5'` for Python 3.5-3.8).
Replace `@inject.param('dependency_name', DependencyType)` with `@inject.params(dependency_name=DependencyType)`.Call `inject.configure(config, bind_in_runtime=False)` to disable implicit runtime binding. This will cause `inject.instance()` or injection to raise an `InjectorException` immediately if a binding is not explicitly provided.
Define and bind custom provider functions (e.g., `binder.bind_to_provider(MyScopedDep, my_custom_scope_provider_func)`) for dependencies that require non-singleton lifetimes.
Ensure the 'inject' library is installed for your active Python environment using pip: `pip install inject`.
Verify that all dependencies are correctly bound in the `inject.configure` function using `binder.bind(DependencyType, to=DependencyImplementation)` or `binder.bind_to_provider` or `binder.bind_to_constructor`. Ensure that the types in your annotations match the registered bindings.
Explicitly bind the missing dependency in your `inject.configure` function, for example: `binder.bind(YourDependency, to=YourDependencyImplementation)`. Alternatively, if runtime binding is desired, remove `bind_in_runtime=False` from `inject.configure` (though this is generally not recommended for robust applications).
Use `@inject.autoparams` on the `__init__` method of a class for constructor injection. For other methods, consider injecting dependencies into the constructor and then using `self.dependency` within the method, or explicitly define the dependencies as arguments to the method if they are context-specific and then call `inject.instance()` or `inject.params()` if method injection is truly needed and supported for that specific case. The `inject` library generally favors constructor injection for class dependencies.
No dependency data recorded yet.