python 3+的依赖注入容器。使用Python3注释为应该注入的组件提供提示。
dic的Python项目详细描述
驾驶员信息中心
python 3+的依赖注入容器部分受Autofac影响。dic的目标是成为一个小小的“不受欢迎”的框架来帮助 通过依赖注入实现ioc。dic使用python 3注释为应该注入的组件提供提示。
文档
DIC文档可通过Read the Docs获得。
安装
- DIC可通过PIP获得:
pip install dic
功能
目前,DIC支持:
- 类的构造函数注入
- 工厂与懒惰的关系
- 注册途径:
- 注册类的构造函数匹配
- 自定义回调
- 预先创建的实例
- 生存期范围:
- 每个依赖项的实例
- 单实例
快速示例
- 如何使用DIC的快速示例:
import dic class SimpleThing(object): def say(self, message): print(message) class RequiresThing(object): def __init__(self, thing: SimpleThing): self.thing = thing def say(self, message): self.thing.say(message) # build the container builder = dic.container.ContainerBuilder() builder.register_class(SimpleThing) builder.register_class(RequiresThing, component_scope=dic.scope.SingleInstance) container = builder.build() # use the container # Note there'll only be one of these due to SingleInstance scoping during build x = container.resolve(RequiresThing) x.say("my message")
关系
DIC支持基本关系:
dic.rel.Lazy
-在首次使用依赖项之前不要创建它dic.rel.Factory
-组件希望创建其他组件。生命周期范围是受尊重的。支持自定义参数。
- 使用工厂:
import dic class SimpleThing(object): def __init__(self, special_argument): self.special_argument = special_argument class BuildsThings(object): def __init__(self, thing_factory: dic.rel.Factory(SimpleThing)): self.thing_factory = thing_factory def build_me_a_thing(self): # builds a new thing using the injected factory # Note that custom arguments can be provided here self.thing_factory(special_argument="My super special argument") # build the container builder = dic.container.ContainerBuilder() builder.register_class(SimpleThing) builder.register_class(BuildsThing) container = builder.build() # use the container x = container.resolve(BuildsThing) # use it thing = x.build_me_a_thing() # ...
常见问题解答
- DIC线程安全吗?
Yes.dic.rel.Lazy
anddic.container.Container.resolve()
are thread-safe. As a result, do not store the component_context given toregister_callback
callbacks, as thread-safety is enforced at the container.resolve() level.
- 我能定义自己的范围吗?
Yes. Derive a scope from dic.scope.Scope
. Scopes can be used to provide lifetime for a calling thread, for example