FastAPI项目添加服务的标准方案:类同.NET Core的依赖注入实现
FastAPI 依赖注入实现方案(对齐.NET Core风格)
FastAPI内置完整的依赖注入系统,无需额外第三方库,完全可以实现类似.NET Core的服务注册与注入流程,下面是针对你的需求的具体实现步骤:
1. 定义服务与抽象接口(可选但推荐)
和.NET中定义接口+实现类的方式一致,你可以先抽象出服务接口,再编写具体实现:
# ./services/my_helper.py from abc import ABC, abstractmethod from datetime import datetime # 抽象接口(对应.NET的Interface) class IHealthService(ABC): @abstractmethod def get_health_status(self) -> dict: pass # 具体服务实现类 class MyHelper(IHealthService): def get_health_status(self) -> dict: return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}
2. 注册服务到FastAPI容器
对应.NET Core在Startup.cs中注册服务的步骤,FastAPI提供了三种生命周期的注册方式,和.NET的生命周期一一对应:
# main.py from fastapi import FastAPI from services.my_helper import IHealthService, MyHelper app = FastAPI() # 注册单例服务(全局唯一实例,对应.NET Singleton) app.add_singleton(IHealthService, MyHelper) # 若需请求级作用域(每个请求新建实例,对应.NET Scoped) # app.add_scoped(IHealthService, MyHelper) # 若需瞬时实例(每次注入都新建,对应.NET Transient) # app.add_transient(IHealthService, MyHelper)
3. 在路由中注入并调用服务
直接在路由函数参数中声明依赖,FastAPI会自动从容器中解析实例,和.NET的构造注入/参数注入逻辑一致:
from fastapi import Depends @app.get("/health") async def health_check(health_service: IHealthService = Depends()): # 调用服务方法 return health_service.get_health_status()
关键说明
- FastAPI的DI系统基于Starlette框架实现,原生支持类型提示解析,无需额外配置
- 如果不需要抽象接口,也可以直接注册并注入具体类(比如直接注册
MyHelper,路由中声明health_service: MyHelper = Depends()) - 测试时可以通过
app.dependency_overrides替换服务实现,和.NET的测试替换逻辑类似
内容的提问来源于stack exchange,提问作者VSO
相关产品推荐
相关产品推荐

