Package: di-container
Dependency Injection ContainerFull featured, flexible and fluent IoC solution for PythonPyPidi_container can be installed fromPyPi.The CodeBasics:Types, callables and values can be registered into a container and bound to either a dependency type, or a name.
Registration is independent of dependency order: A dependency can be registered after the dependent type, as long as they are both registered before resolving.fromdi_container.containerimportContainercontainer=Container(name='container')container.register_callable(main).to_name('main_func')container.register_value(app_config['logging']['log_path']).to_name('log_path')container.register_type(FileLogger).to_type(ILogger)Multiplicity:Types and callables can be registered asInstantiation.Singleton(default), or asInstantiation.MultiInstance.fromdi_container.containerimportContainer,Instantiationcontainer=Container(name='container')container.register_callable(ConnectionFactory.new_udp_connection,instantiation=Instantiation.MultiInstance).to_type(IConnection)Type checks:Registeringto_typetype checks against the given dependency type. When registeringto_name, an optional type can be given, in order to make the same check.
If the check fails, aTypeErroris raised.fromdi_container.containerimportContainercontainer=Container(name='container')container.register_value(app_config['network']['http_port']).to_name('port',int)Manual assignment:Type initializers and callables can have some, or all, of their arguments assigned values explicitly.
The rest will be resolved at resolve time.fromdi_container.containerimportContainer,Instantiationcontainer=Container(name='container')container.register_callable(ConnectionFactory.new_udp_connection,instantiation=Instantiation.MultiInstance).to_type(IConnection).with_params(host='localhost',port=12345)Resolving order:Resolving a registered type, or name, will attempt to resolve any needed arguments for type initializers, or callables, recursively.
First, with values given inwith_params, second, with arguments' type annotations (please use them 🙂), and then, with declared default values.When a dependency is registeredto_name, it cannot be automatically inferred by type annotation.
A container's default behavior is to use an argument's name to lookup ato_nameregistration as a last attempt to resolve an argument.
This behavior can be changed if it's deemed to be too risky, and dependency names can be assigned explicitly when needed, usingwith_name_bindings.The full order of resolution attempts for a parameter is:Given value, in the form ofwith_params(param=value). The value of param will be the given value.Name binding, in the form ofwith_name_bindings(param='name_binding'). The value of param will be the resolution of the name 'name_binding'.Type annotation. If the parameter has a type annotation (type hint), then the value of param will be the resolution of this type.Ifparam_names_as_bindingsisTrue, The container will attempt to resolve the param name itself.
If successful, the value of param will be the resolution of the parameter's name.Lastly, if a default value is defined for the parameter, it will be used. The value of param will be its default value.
If, however,prefer_defaultsisTruein callingresolve_typeorresolve_name,
the default value will be used if no explicit value or binding was given (Nowith_paramsorwith_name_bindingsfor that parameter),
instead of trying to resolve the type annotation or parameter name.fromdi_container.containerimportContainer,Instantiationcontainer=Container(name='container',param_names_as_bindings=False)container.register_callable(ConnectionFactory.new_udp_connection,instantiation=Instantiation.MultiInstance).to_type(IConnection).with_name_bindings(host='host_ip',port='port')container.register_value(app_config['network']['ip']).to_name('host_ip',str)container.register_value(app_config['network']['http_port']).to_name('port',int)Sub-containers:Sub-containers can help when writing several packages, or sub-systems, or just to organize a large amount of dependencies.
The resolving process will try to resolve from the current container and if no match is found, will try to resolve using each sub-container (and its sub-containers recursively) in the order they were added.
Containers are initialized with names for identification in error messages.fromdi_container.containerimportContainerbase_container=Container(name='base')# register config values and core classesbase_container.register_value(app_config['logging']['log_path']).to_name('log_path')base_container.register_value(app_config['database']['database_url']).to_name('database_url',str)base_container.register_type(FileLogger).to_type(ILogger)base_container.register_type(NoSqlDatabase).to_type(IDatabase)main_container=Container('main')# register main class and entry pointmain_container.register_callable(main).to_name('main_function').with_name_bindings(main_manager='main_class')main_container.register_type(MainManager).to_name('main_class').with_name_bindings(internal_comm='int_comm',external_comm='ext_comm')comm_container=Container('comm')# register communication classescomm_container.register_type(UdpCommunicator).to_name('int_comm',ICommunicator)comm_container.register_type(HttpCommunicator).to_name('ext_comm',ICommunicator)# setting sub containerscomm_container.add_sub_container(base_container)main_container.add_sub_container(base_container)main_container.add_sub_container(comm_container)# activating the main functionmain_container.resolve_name('main_function')To DoSome features that are being considered:Configuration registration.Binding to members of registered items.Registration of collections of values.Display of dependency tree (forest).MoreAnexampleis available in the git repository.