如何在python-dependency-injector外层容器中链接循环依赖的子容器?
解决子容器间循环依赖的方案
在领域模块使用子容器组织时,常会遇到UserContainer与PaymentContainer这类循环依赖的情况,可通过依赖注入容器的延迟解析特性来处理,具体实现如下:
修改后的完整代码
from dataclasses import dataclass import dependency_injector.containers as containers import dependency_injector.providers as providers @dataclass class UserService: payments: "PaymentsService" def user_action(self): print("user action") self.payments.payment_action() @dataclass class PaymentsService: users: UserService def payment_action(self): print("payment action") class UserContainer(containers.DeclarativeContainer): payments = providers.DependenciesContainer() service = providers.Factory(UserService, payments=payments.service) class PaymentContainer(containers.DeclarativeContainer): users = providers.DependenciesContainer() service = providers.Factory(PaymentsService, users=users.service) class ApplicationContainer(containers.DeclarativeContainer): # 利用lambda延迟引用自身容器,解决循环绑定 users = providers.Container(UserContainer, payments=lambda self: self.payments) payments = providers.Container(PaymentContainer, users=users)
核心说明
- 使用
lambda self: self.payments作为UserContainer的payments参数,借助容器的延迟解析机制,当UserContainer需要依赖时,会从ApplicationContainer中获取已初始化的payments容器。 - 这种方式既完成了两个子容器的循环绑定,又能保证服务实例在实际调用时正确获取到依赖对象。
验证运行
可以添加以下代码验证功能正常:
if __name__ == "__main__": app_container = ApplicationContainer() user_service = app_container.users.service() payment_service = app_container.payments.service() user_service.user_action() payment_service.payment_action()
内容的提问来源于stack exchange,提问作者Arseniy
相关产品推荐
相关产品推荐

