知识卡片

普通读书笔记卡 · 3498.a

依赖注入让实现可替换

理解等级:中级

依赖注入是实现 [[控制反转由外部提供依赖]] 的一种方式:业务服务把仓储作为构造参数接收,由调用者创建并配置具体实现。这样同一服务可在不同环境接入不同仓储,也便于测试时传入替身;服务本身无需知道依赖如何初始化。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    原书出处

    参考来源

    - 位置:《Microservice APIs》第 7 章《Service implementation patterns for microservices》(源文件:_epub-src/OEBPS/Text/07.htm) - 结论依据:原文定义依赖注入是在运行时提供代码依赖,并给出 `OrdersService.__init__(orders_repository)` 的构造参数例子及替换、测试收益。 - 原始内容:Dependency injection is a software development pattern whereby we supply code dependencies at runtime. This helps us decouple our components from the specific implementation details of the code they depend on, since they don’t need to know how to configure and instantiate their dependencies.