python 3+的依赖注入容器。使用Python3注释为应该注入的组件提供提示。

dic的Python项目详细描述


驾驶员信息中心

python 3+的依赖注入容器部分受Autofac影响。dic的目标是成为一个小小的“不受欢迎”的框架来帮助 通过依赖注入实现ioc。dic使用python 3注释为应该注入的组件提供提示。

versionbuilddocs

文档

DIC文档可通过Read the Docs获得。

安装

DIC可通过PIP获得:
pip install dic

功能

目前,DIC支持:

  1. 类的构造函数注入
  2. 工厂与懒惰的关系
  3. 注册途径:
    1. 注册类的构造函数匹配
    2. 自定义回调
    3. 预先创建的实例
  4. 生存期范围:
    1. 每个依赖项的实例
    2. 单实例

快速示例

如何使用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支持基本关系:

  1. dic.rel.Lazy-在首次使用依赖项之前不要创建它
  2. 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()
# ...

常见问题解答

  1. DIC线程安全吗?
Yes. dic.rel.Lazy and dic.container.Container.resolve() are thread-safe. As a result, do not store the component_context given to register_callback callbacks, as thread-safety is enforced at the container.resolve() level.
  1. 我能定义自己的范围吗?
Yes. Derive a scope from dic.scope.Scope. Scopes can be used to provide lifetime for a calling thread, for example

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
GridLayout不工作的java问题   java Restlet请求对象不包含身份验证信息   java使用Cucumber为每个正在运行的线程创建一个TestNG runner类   java在平面文件中存储并跟踪它们?   类Lcom/google/firebase/FirebaseApp中没有虚拟方法zzbzo()Z;或者它的超类   java如何在安卓中创建字符串模式   可从Java访问的树莓PI传感器   java 50+GB分隔文件中的大致行数   是否有Java进程内数据库,允许从多表虚拟机访问?   当我使用ArrayList时,HashMap中的Java ArrayList会导致HashMap中的数据被删除。去除   如何将值存储在最佳java集合结构中   java消息Servlet。servlet appServlet的init()引发异常   java正在使用Spring引导生成空日志文件   c#在访问实例变量时使用this关键字是否更有效?   java JScrollPane滚动到最后添加的行   java Vertx抛出IllegalStateException:响应已被写入   java Liferay以编程方式更改portlet列   java下载单个s3对象并将它们合并到单个文件中   java spark数据帧将JSON转换为ORC满足“列模糊异常”