I’m familiar with dependency injecting and I was trying to do something I have seen in the past in other frameworks (spring Autowired annotation).
I have the following 2 classes :
class MyServerConfig:
def __init__(self):
serviceA_host = getenv("SERVICE_A_HOST")
ServiceA_port = getenv("SERVICE_A_PORT")
self._serviceA_addr = f"{serviceA_host}:{ServiceA_port}"
class DependencyContainer:
def __init__(self, config: ServiceConfig):
serviceA_channel = grpc.insecure_channel(config._serviceA_addr)
self._serviceA_client = (
SomeGrpcStub(serviceA_channel)
)
def service_a_client():
return self.serviceA_client
In my main.py
I initialize both classes and pass them as dependencies to my routes :
config = MyServerConfig()
dependency_container = DependencyContainer(config)
And I tried to pass them as dependencies to my inner routes :
def get_dependency_container() -> DependencyContainer:
return dependency_container
def get_server_config() -> MyServerConfig:
return config
shared_dependencies = [
Depends(get_service_config),
Depends(get_dependency_container),
]
app.include_router(
somemodule.products_router_v1(),
dependencies=shared_dependencies,
)
My router code:
def products_router_v1():
products_router = APIRouter(
prefix="/products",
)
@products_router.post(
"",
)
def register_product(
save_request: SaveProductRequest,
http_request: Request,
dependency_container: DependencyContainer = Depends(),
) -> Response
I was hoping that fastapi will understand that DependencyContainer
is available in the route dependencies and will inject it but it doesnt do that.
My goal is to create the clients in one place (main.py) and inject the relevant clients to the relevant endpoints. I prefer to create globals only in my main.py and not in other modules.
Is there a way to implement this injection via fastapi ?