Python 进阶
Python 协程实现原理
dict 和 set 实现原理
Python 线程安全
Python 抽象语法树(AST)
Python 日志输出
Python 扩展入门(一)
Python 程序执行原理
Python 垃圾回收
Python 动态创建类
检查工具
PyFrameObject
yield 生成器工作原理
dict 设计与实现
Python 性能分析原理
PyCodeObject
Python 弱引用
Python 性能分析原理(二)
Python 源码分析(一)
Python Annotated
Python 依赖注入
python freelist
python代码编译成pyc
Python mmap 内存映射文件
Python值得学习的内容
async Future 对象
asyncio loop的实现
asyncio.sleep 的实现
asyncio 原理
Python 代码加密
Python Token类型
Python 扩展入门(二)
Python 性能优化
本文档使用 MrDoc 发布
-
+
首页
Python 依赖注入
### 什么是依赖注入? 依赖注入是一种设计模式,它的核心思想是: > 类不应该自己创建依赖的对象,而是应该从外部接收依赖。 ### 示例 没有使用依赖注入的例子: ``` class Service: def __init__(self): # 类自己创建依赖,这不是依赖注入 self.db = Database(url="postgresql://localhost:5432") self.cache = Cache(address="redis://localhost:6379") ``` 使用依赖注入的例子: 1. 基础的依赖注入: ``` from dataclasses import dataclass @dataclass class Database: url: str @dataclass class Cache: address: str class Service: def __init__(self, db: Database, cache: Cache): # 依赖从外部注入 self.db = db self.cache = cache # 使用 db = Database(url="postgresql://localhost:5432") cache = Cache(address="redis://localhost:6379") service = Service(db=db, cache=cache) ``` 2. 使用依赖注入容器: ``` from dependency_injector import containers, providers class Container(containers.DeclarativeContainer): # 配置数据库连接 database = providers.Singleton( Database, url="postgresql://localhost:5432" ) # 配置缓存连接 cache = providers.Singleton( Cache, address="redis://localhost:6379" ) # 配置服务 service = providers.Singleton( Service, db=database, cache=cache ) # 使用 container = Container() service = container.service() ``` ### 依赖注入的优势 1. 解耦 ``` # 不好的做法:强耦合 class Service: def __init__(self): self.db = Database("postgresql://localhost:5432") # 好的做法:松耦合 class Service: def __init__(self, db: Database): self.db = db ``` 2. 单一职责 ``` class Service: # 专注于业务逻辑,而不是如何创建和管理依赖 def __init__(self, db: Database, cache: Cache): self.db = db self.cache = cache def get_user(self, user_id: int): cached_user = self.cache.get(f"user:{user_id}") if cached_user: return cached_user return self.db.get_user(user_id) ``` ### 常见的依赖注入框架 - `dependency-injector` - `injector` - `fastapi (内置依赖注入系统)` ### 使用 FastAPI 的依赖注入示例 ``` from fastapi import Depends, FastAPI app = FastAPI() def get_db(): db = Database("postgresql://localhost:5432") try: yield db finally: db.close() @app.get("/users/{user_id}") def read_user(user_id: int, db: Database = Depends(get_db)): return db.get_user(user_id) ``` ### 总结 依赖注入是一种强大的设计模式,它可以帮助我们编写更清晰、更易测试和更易维护的代码。
gaojian
2025年1月23日 19:03
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
Markdown文件
分享
链接
类型
密码
更新密码