{"id":13458939,"url":"https://github.com/nightblure/injection","last_synced_at":"2025-09-12T22:33:31.216Z","repository":{"id":250315001,"uuid":"834104785","full_name":"nightblure/injection","owner":"nightblure","description":"Dependency injection, works with FastAPI, Litestar, Django, Flask (Python 3.8-3.13). Light replacement with new features for dependency-injector","archived":false,"fork":false,"pushed_at":"2025-04-21T15:24:46.000Z","size":422,"stargazers_count":16,"open_issues_count":4,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-09-07T02:53:26.529Z","etag":null,"topics":["dependency-injection","dependency-injection-container","dependency-injection-framework","dependency-injector","di","di-container","injection","injector","ioc-container","singleton"],"latest_commit_sha":null,"homepage":"https://injection.readthedocs.io/latest/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nightblure.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-07-26T12:32:23.000Z","updated_at":"2025-07-15T05:56:09.000Z","dependencies_parsed_at":"2024-12-14T16:34:25.231Z","dependency_job_id":"e5472836-c211-4565-b515-98605f6fe6c8","html_url":"https://github.com/nightblure/injection","commit_stats":null,"previous_names":["nightblure/injection"],"tags_count":16,"template":false,"template_full_name":null,"purl":"pkg:github/nightblure/injection","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nightblure%2Finjection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nightblure%2Finjection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nightblure%2Finjection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nightblure%2Finjection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nightblure","download_url":"https://codeload.github.com/nightblure/injection/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nightblure%2Finjection/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274063009,"owners_count":25216019,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-07T02:00:09.463Z","response_time":67,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","dependency-injection-container","dependency-injection-framework","dependency-injector","di","di-container","injection","injector","ioc-container","singleton"],"created_at":"2024-07-31T09:01:00.030Z","updated_at":"2025-09-12T22:33:31.202Z","avatar_url":"https://github.com/nightblure.png","language":"Python","readme":"# Injection\n\n![PyPI - Version](https://img.shields.io/pypi/v/deps-injection?label=pypi%20version\u0026color=012111012)\n![GitHub License](https://img.shields.io/github/license/nightblure/injection?color=012111012)\n\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/deps-injection)\n\n[![Latest Release](https://github.com/nightblure/injection/actions/workflows/publish.yml/badge.svg)](https://github.com/nightblure/injection/actions/workflows/publish.yml)\n[![Documentation Status](https://readthedocs.org/projects/injection/badge/?version=latest)](https://injection.readthedocs.io/en/latest/?badge=latest)\n\n[![Tests And Linting](https://github.com/nightblure/injection/actions/workflows/ci.yml/badge.svg)](https://github.com/nightblure/injection/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/nightblure/injection/graph/badge.svg?token=2ZTFBlJqTb)](https://codecov.io/gh/nightblure/injection)\n\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)\n[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)\n[![MyPy Strict](https://img.shields.io/badge/mypy-strict-blue)](https://mypy.readthedocs.io/en/stable/getting_started.html#strict-mode-and-configuration)\n\n![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/nightblure/injection/total?color=102255102\u0026label=Total%20downloads)\n![PyPI - Month Downloads](https://img.shields.io/pypi/dm/deps-injection?color=102255102\u0026label=Month%20downloads)\n![GitHub Repo stars](https://img.shields.io/github/stars/nightblure/injection)\n\n---\n\nEasy dependency injection for all, works with Python 3.8-3.13. Main features and advantages:\n* support **Python 3.8-3.13**;\n* works with **FastAPI, **Litestar**, Flask** and **Django REST Framework**;\n* support **dependency** **injection** via `Annotated` in `FastAPI`;\n* support **async injections**;\n* support [**auto injection by types**](https://injection.readthedocs.io/latest/injection/auto_injection.html); \n* [**resources**](https://injection.readthedocs.io/latest/providers/resource.html) with **function scope**;\n* no **wiring**;\n* **overriding** dependencies for testing;\n* **100%** code coverage;\n* the code is fully **typed** and checked with [mypy](https://github.com/python/mypy);\n* good [documentation](https://injection.readthedocs.io/latest/);\n* intuitive and almost identical api with [dependency-injector](https://github.com/ets-labs/python-dependency-injector),\nwhich will allow you to easily migrate to injection\n(see [migration from dependency injector](https://injection.readthedocs.io/latest/dev/migration-from-dependency-injector.html));\n\n---\n\n## Installation\n```shell\npip install deps-injection\n```\n\n## Compatibility between web frameworks and injection features\n| Framework                                                                | Dependency injection with @inject | Overriding providers |    Dependency injection with @autoinject    |\n|--------------------------------------------------------------------------|:---------------------------------:|:--------------------:|:-------------------------------------------:|\n| [FastAPI](https://github.com/fastapi/fastapi)                            |                 ✅                 |          ✅           |                      ➖                      |\n| [Flask](https://github.com/pallets/flask)                                |                 ✅                 |          ✅           |                      ✅                      |\n| [Django REST Framework](https://github.com/encode/django-rest-framework) |                 ✅                 |          ✅           |                      ✅                      |\n| [Litestar](https://github.com/litestar-org/litestar)                     |                 ✅                 |          ✅           |                      ➖                      |                           ➖                            |\n\n\n## Quickstart with FastAPI, SQLAlchemy and pytest (sync sqlite)\n```python3\nfrom contextlib import contextmanager\nfrom random import Random\nfrom typing import Annotated, Any, Callable, Dict, Iterator\n\nimport pytest\nfrom fastapi import Depends, FastAPI\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import Session, sessionmaker\nfrom starlette.testclient import TestClient\n\nfrom injection import DeclarativeContainer, Provide, inject, providers\n\n\n@contextmanager\ndef db_session_resource(session_factory: Callable[..., Session]) -\u003e Iterator[Session]:\n    session = session_factory()\n    try:\n        yield session\n    except Exception:\n        session.rollback()\n    finally:\n        session.close()\n\n\nclass SomeDAO:\n    def __init__(self, db_session: Session) -\u003e None:\n        self.db_session = db_session\n\n    def get_some_data(self, num: int) -\u003e int:\n        stmt = text(\"SELECT :num\").bindparams(num=num)\n        data: int = self.db_session.execute(stmt).scalar_one()\n        return data\n\n\nclass DIContainer(DeclarativeContainer):\n    db_engine = providers.Singleton(\n        create_engine,\n        url=\"sqlite:///db.db\",\n        pool_size=20,\n        max_overflow=0,\n        pool_pre_ping=False,\n    )\n\n    session_factory = providers.Singleton(\n        sessionmaker,\n        db_engine.cast,\n        autoflush=False,\n        autocommit=False,\n    )\n\n    db_session = providers.Resource(\n        db_session_resource,\n        session_factory=session_factory.cast,\n        function_scope=True,\n    )\n\n    some_dao = providers.Factory(SomeDAO, db_session=db_session.cast)\n\n\nSomeDAODependency = Annotated[SomeDAO, Depends(Provide[DIContainer.some_dao])]\n\napp = FastAPI()\n\n\n@app.get(\"/values/{value}\")\n@inject\nasync def sqla_resource_handler_async(\n    value: int,\n    some_dao: SomeDAODependency,\n) -\u003e Dict[str, Any]:\n    value = some_dao.get_some_data(num=value)\n    return {\"detail\": value}\n\n\n@pytest.fixture(scope=\"session\")\ndef test_client() -\u003e TestClient:\n    client = TestClient(app)\n    return client\n\n\ndef test_sqla_resource(test_client: TestClient) -\u003e None:\n    rnd = Random()\n    random_int = rnd.randint(-(10**6), 10**6)\n\n    response = test_client.get(f\"/values/{random_int}\")\n\n    assert response.status_code == 200\n    assert not DIContainer.db_session.initialized\n    body = response.json()\n    assert body[\"detail\"] == random_int\n\n```\n\n## Quickstart with FastAPI, SQLAlchemy and pytest (async sqlite)\n```python\nfrom contextlib import asynccontextmanager\nfrom random import Random\nfrom typing import Annotated, Any, Callable, Dict, AsyncIterator\n\nimport pytest\nfrom fastapi import Depends, FastAPI\nfrom sqlalchemy import text\nfrom sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession\nfrom starlette.testclient import TestClient\n\nfrom injection import DeclarativeContainer, Provide, inject, providers\n\n\n@asynccontextmanager\nasync def db_session_resource(session_factory: Callable[..., AsyncSession]) -\u003e AsyncIterator[AsyncSession]:\n    session = session_factory()\n    try:\n        yield session\n    except Exception:\n        await session.rollback()\n    finally:\n        await session.close()\n\n\nclass SomeDAO:\n    def __init__(self, db_session: AsyncSession) -\u003e None:\n        self.db_session = db_session\n\n    async def get_some_data(self, num: int) -\u003e int:\n        stmt = text(\"SELECT :num\").bindparams(num=num)\n        result = await self.db_session.execute(stmt)\n        data: int = result.scalar_one()\n        return data\n\n\nclass DIContainer(DeclarativeContainer):\n    # need to install aiosqlite and greenlet\n    db_engine = providers.Singleton(\n        create_async_engine,\n        url=\"sqlite+aiosqlite:///db.db\",\n        pool_pre_ping=False,\n    )\n\n    session_factory = providers.Singleton(\n        async_sessionmaker,\n        db_engine.cast,\n        autoflush=False,\n        autocommit=False,\n    )\n\n    db_session = providers.Resource(\n        db_session_resource,\n        session_factory=session_factory.cast,\n        function_scope=True,\n    )\n\n    some_dao = providers.Factory(SomeDAO, db_session=db_session.cast)\n\n\nSomeDAODependency = Annotated[SomeDAO, Depends(Provide[DIContainer.some_dao])]\n\napp = FastAPI()\n\n\n@app.get(\"/values/{value}\")\n@inject\nasync def sqla_resource_handler_async(\n        value: int,\n        some_dao: SomeDAODependency,\n) -\u003e Dict[str, Any]:\n    value = await some_dao.get_some_data(num=value)\n    return {\"detail\": value}\n\n\n@pytest.fixture(scope=\"session\")\ndef test_client() -\u003e TestClient:\n    client = TestClient(app)\n    return client\n\n\ndef test_async_sqla_resource(test_client: TestClient) -\u003e None:\n    rnd = Random()\n    random_int = rnd.randint(-(10 ** 6), 10 ** 6)\n\n    response = test_client.get(f\"/values/{random_int}\")\n\n    assert response.status_code == 200\n    assert not DIContainer.db_session.initialized\n    body = response.json()\n    assert body[\"detail\"] == random_int\n\n```\n","funding_links":[],"categories":["Software"],"sub_categories":["DI Frameworks / Containers"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnightblure%2Finjection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnightblure%2Finjection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnightblure%2Finjection/lists"}