linkd.ext.starlette¶
Extension module adding support for using linkd-based dependency injection with Starlette.
See the examples directory for a full working application using this module.
- final class Contexts[source]¶
Collection of the dependency injection context values linkd.ext.starlette uses.
- REQUEST = 'linkd.contexts.http.request'¶
DI context used during HTTP request handling.
- ROOT = 'linkd.contexts.root'¶
The root DI context - ALL other contexts are built with this as the parent.
- class DiContextMiddleware(app: ASGIApp, manager: _solver.DependencyInjectionManager)[source]¶
Middleware class which handles setting up a DI context for each HTTP request.
- Parameters:
app – The app this middleware will be applied to.
manager – The dependency injection manager to use when entering the DI context.
Example
from starlette.applications import Starlette from starlette.middleware import Middleware import linkd manager = linkd.DependencyInjectionManager() middleware = [ Middleware(linkd.ext.starlette.DiContextMiddleware, manager=manager), ] app = Starlette(routes=..., lifetime=..., middleware=middleware)
- inject(func: InjectedCallableT) InjectedCallableT[source]¶
Specialised decorator enabling linkd dependency injection for starlette route handlers. This decorator must be used instead of the standard
inject()decorator so that starlette does not treat injection-enabled functions as ASGI apps instead of request/response functions.If you are enabling DI for any function other than a route handler then the standard decorator will still work.
- Parameters:
func – The function to enable DI for.
- Returns:
The function with dependency injection enabled.
Note
ASGI route handlers are not supported when using this decorator, you should use the standard
inject()decorator instead.Example
from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import Response from starlette.routing import Route import linkd @linkd.ext.starlette.inject async def some_handler(request: Request, dependency: SomeDependency) -> Response: ... routes = [ Route("/foo", some_handler), ] manager = linkd.DependencyInjectionManager() middleware = [ Middleware(linkd.ext.starlette.DiContextMiddleware, manager=manager), ] app = Starlette(routes=routes, lifetime=..., middleware=middleware)