首页
/ Injector - Python依赖注入框架技术文档

Injector - Python依赖注入框架技术文档

2024-12-17 17:29:07作者:韦蓉瑛

1. 安装指南

安装方式

您可以通过PyPI(Python软件包索引)使用pip来安装Injector。请运行以下命令:

pip install injector

确保您的Python环境版本为CPython 3.8+ 或 PyPy 3实现Python 3.8+。

2. 项目的使用说明

Injector 是一个Python依赖注入框架,旨在通过自动和传递性地提供依赖来简化大型应用程序的编码工作。它鼓励通过模块使用良好分隔的代码。

快速示例

以下是使用Injector的一个快速示例:

from injector import Injector, inject

class Inner:
    def __init__(self):
        self.forty_two = 42

class Outer:
    @inject
    def __init__(self, inner: Inner):
        self.inner = inner

injector = Injector()
outer = injector.get(Outer)
print(outer.inner.forty_two)  # 输出 42

完整示例

以下是一个完整的示例,展示Injector的使用方法:

from injector import Module, provider, Injector, inject, singleton
import sqlite3

class RequestHandler:
    @inject
    def __init__(self, db: sqlite3.Connection):
        self._db = db

    def get(self):
        cursor = self._db.cursor()
        cursor.execute('SELECT key, value FROM data ORDER by key')
        return cursor.fetchall()

class Configuration:
    def __init__(self, connection_string):
        self.connection_string = connection_string

def configure_for_testing(binder):
    configuration = Configuration(':memory:')
    binder.bind(Configuration, to=configuration, scope=singleton)

class DatabaseModule(Module):
    @singleton
    @provider
    def provide_sqlite_connection(self, configuration: Configuration) -> sqlite3.Connection:
        conn = sqlite3.connect(configuration.connection_string)
        cursor = conn.cursor()
        cursor.execute('CREATE TABLE IF NOT EXISTS data (key PRIMARY KEY, value)')
        cursor.execute('INSERT OR REPLACE INTO data VALUES ("hello", "world")')
        return conn

injector = Injector([configure_for_testing, DatabaseModule()])
handler = injector.get(RequestHandler)
print(tuple(map(str, handler.get()[0])))  # 输出 ('hello', 'world')

# 验证单例
print(injector.get(Configuration) is injector.get(Configuration))  # 输出 True
print(injector.get(sqlite3.Connection) is injector.get(sqlite3.Connection))  # 输出 True

3. 项目API使用文档

  • @inject:用于标记类的构造函数,自动注入所需的依赖。
  • Injector:用于创建和配置依赖注入环境。
  • Injector.get:从Injector获取特定类型的实例。
  • Injector.create_object:创建一个对象,自动注入其依赖。
  • Module:定义一组绑定和提供者。
  • provider:用于定义提供者函数,该函数负责生成依赖对象。
  • singleton:用于指定绑定对象的生命周期为单例。

4. 项目安装方式

请参考上文“安装指南”中的步骤进行安装。

通过上述技术文档,您应该能够了解如何安装和使用Injector依赖注入框架。在大型项目中使用它可以帮助您更好地组织代码,提高代码的可维护性和扩展性。

热门项目推荐
相关项目推荐

项目优选

收起
Python-100-DaysPython-100-Days
Python - 100天从新手到大师
Python
610
115
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
286
79
mdmd
✍ WeChat Markdown Editor | 一款高度简洁的微信 Markdown 编辑器:支持 Markdown 语法、色盘取色、多图上传、一键下载文档、自定义 CSS 样式、一键重置等特性
Vue
111
25
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
60
48
RuoYi-Cloud-Vue3RuoYi-Cloud-Vue3
🎉 基于Spring Boot、Spring Cloud & Alibaba、Vue3 & Vite、Element Plus的分布式前后端分离微服务架构权限管理系统
Vue
45
29
go-stockgo-stock
🦄🦄🦄AI赋能股票分析:自选股行情获取,成本盈亏展示,涨跌报警推送,市场整体/个股情绪分析,K线技术指标分析等。数据全部保留在本地。支持DeepSeek,OpenAI, Ollama,LMStudio,AnythingLLM,硅基流动,火山方舟,阿里云百炼等平台或模型。
Go
1
0
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
205
57
MateChatMateChat
前端智能化场景解决方案UI库,轻松构建你的AI应用,我们将持续完善更新,欢迎你的使用与建议。 官网地址:https://matechat.gitcode.com
376
36
RuoYi-VueRuoYi-Vue
🎉 基于SpringBoot,Spring Security,JWT,Vue & Element 的前后端分离权限管理系统,同时提供了 Vue3 的版本
Java
182
44
frogfrog
这是一个人工生命试验项目,最终目标是创建“有自我意识表现”的模拟生命体。
Java
8
0