提问人:Arseniy 提问时间:11/15/2023 更新时间:11/15/2023 访问量:40
python-dependency-injector 循环互相关的包
python-dependency-injector circularly interrelated packages
问:
使用子容器在应用程序中组织层时,它们之间可能不会有循环依赖关系。但是,对于域,情况并非如此。
@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):
users = providers.Container(UserContainer, payments=???)
payments = providers.Container(PaymentContainer, users=users)
如果在最外层的容器中,我想链接具有循环依赖关系的包,该怎么办?
答:
1赞
Stk Ove
11/15/2023
#1
您可以在 ApplicationContainer 类中添加此行
class ApplicationContainer(containers.DeclarativeContainer):
users = providers.Container(UserContainer)
payments = providers.Container(PaymentContainer)
users.override_providers({UserContainer.payments: payments.service})
payments.override_providers({PaymentContainer.users: users.service})
评论
0赞
Arseniy
11/15/2023
不幸的是,似乎不起作用:users.override_providers({UserContainer.payments: payments})
TypeError: override_providers() takes exactly 1 positional argument (2 given)
0赞
Arseniy
11/15/2023
users.override_providers(payments=payments)
payments.override_providers(users=users)
结果RecursionError
评论