class watson.di.container.IocContainer(config=None)[source]

A simple dependency injection container that can store and retrieve dependencies for an application.

The container is configured via a dict containing the following keys.

A dict of data that can be injected into a dependency. If the value of the key is the same as the name of another dependency then the dependency will be referenced.

A dict of definitions that are to be loaded by the container. Available keys within a definition are as follows.

The qualified name of a class or function
singleton (only load the dependency once) or prototype (instantiate and return a new dependency on each request)
A list or dict of items to be injected into the dependency on instantiation.
A list or dict of methods to be called upon instantiation.
Same as setter

Only ‘item’ is a required key.

A dict of events to be listened for and processors to be called.


container = IocContainer({
    'params': {
        'db.host': 'localhost'
    'definitions': {
        'database': {
            'item': 'db.adapters.MySQL'
            'init': {
                'host': 'db.host',
                'username': 'simon',
                'password': 'test',
                'db': 'test'
db = container.get('database')  # an instance of db.adapters.MySQL

dict – A dict containing the definitions, params and processors.


dict – A cache of already instantiated dependencies.


Initializes the container and set some default configuration options.

Parameters:config (dict) – The params, definitions and processors.

Loads a definition item.

add(name, obj, type_='singleton')[source]

Add an instantiated dependency to the container.

  • name (string) – The name used to reference the dependency
  • obj (mixed) – The dependency to add
  • type (string) – prototype|singleton depending on if it should be instantiated on each IocContainer.get call.
add_definition(name, definition)[source]

Adds a dependency definition to the container.

  • name (string) – The name used to reference the dependency
  • definition (dict) – The definition of the dependency.
attach_processor(event, processor)[source]

Attach a processor to the container.

Attaches a processor to the container that will be triggered on a specific event.

  • event (string) – The name of the event (watson.di.container.POST_EVENT or PRE_EVENT)
  • processor (watson.di.processors.BaseProcessor) – The processor to attach.

Convenience method for retrieving the definitions.

Returns:A dict of params.
Return type:dict

Retrieve a dependency from the container.

Parameters:name (string) – The name of the dependency to retrieve.
Raises:KeyError – If the definition or item within the definition are not specified.
Returns:The dependency
Return type:mixed

Convenience method for retrieving the params.

Returns:A dict of params.
Return type:dict

Update the configuration.

Parameters:config (dict) – The new configuration to update with.