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
- Provider Basics - Register, unregister, and check provider status
- Named Providers - Register multiple providers for the same type
- Resource Management - Manage lifecycle of resources like databases and connections
- Auto-Registration - Automatically register dependencies with decorators
Next Steps: - Scopes - Learn about provider lifecycles - Dependency Injection - Learn how to inject providers - Testing - Learn how to test with providers