sunnydi依赖注入框架
tycoon的Python项目详细描述
sunnydi是 在python中管理和注入依赖项。
它的灵感来自于.net的Autofac 和Guice用于Java。
如何使用
在我们的例子中,我们将为helloservice创建一个ioc模块。
classHelloService(object):defhello(self):return'hello'
创建扩展sunnydi.ioc.module的新配置模块。 模块定义如何创建、销毁对象并将其提供给ioc对象图中的其他对象实例。 在最简单的配置中,我们只需将字符串名称绑定到helloservice类类型:
classHelloModule(Module):defconfigure(self):self.bind('hello_service').to(HelloService)
然后,我们可以创建注入器并像这样解决hello服务:
>>>hello_module=HelloModule()>>>injector=hello_module.create_injector()>>>hello_service=injector.get('hello_service')>>>hello_service.hello()'hello'
解析实例通过构造函数参数提供给使用类。 例如,给定以下类:
classMyClass(object):def__init__(self,hello_service):self._hello_service=hello_servicedefdo_hello(self):returnself._hello_service.hello()
由于 服务的绑定名与myclass构造函数中定义的参数匹配:
>>>my_class_instance=injector.get(MyClass)>>>my_class_instance.do_hello()'hello'
对于高级用法,请签出docs