Skip to content

Providers

Providers are the core of AnyDI. A provider is a function or class that returns an instance of a specific type. After registering a provider with Container, you can use it to resolve dependencies in your application.

Quick Examples

Basic Provider

from anydi import Container

container = Container()

@container.provider(scope="singleton")
def config() -> dict:
    return {"env": "production"}

Named Provider

from typing import Annotated

@container.provider(scope="singleton")
def primary_db() -> Annotated[Database, "primary"]:
    return Database(host="primary.db")

Resource Provider

from typing import Iterator

@container.provider(scope="singleton")
def database() -> Iterator[Database]:
    db = Database()
    db.connect()
    yield db
    db.disconnect()

Auto-Registered Provider

from anydi import singleton

@singleton
class UserService:
    def __init__(self, db: Database) -> None:
        self.db = db

Learn More


Next Steps: - Scopes - Learn about provider lifecycles - Dependency Injection - Learn how to inject providers - Testing - Learn how to test with providers