Overriding of containersΒΆ

Containers can be overridden by other containers. This, actually, means that all of the providers from overriding container will override providers with the same names in overridden container.

There are two ways to override DeclarativeContainer with another container:

Example of overriding container using DeclarativeContainer.override() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""Declarative IoC container overriding example."""

import dependency_injector.containers as containers
import dependency_injector.providers as providers


class Container(containers.DeclarativeContainer):
    """IoC container."""

    sequence_factory = providers.Factory(list)


class OverridingContainer(containers.DeclarativeContainer):
    """Overriding IoC container."""

    sequence_factory = providers.Factory(tuple)


# Overriding `Container` with `OverridingContainer`:
Container.override(OverridingContainer)

# Creating some objects using overridden container:
sequence_1 = Container.sequence_factory([1, 2, 3])
sequence_2 = Container.sequence_factory([3, 2, 1])

# Making some asserts:
assert Container.overridden == (OverridingContainer,)
assert sequence_1 == (1, 2, 3) and sequence_2 == (3, 2, 1)

Example of overriding container using override() decorator:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""Declarative IoC container overriding using `@override()` decorator."""

import dependency_injector.containers as containers
import dependency_injector.providers as providers


class Container(containers.DeclarativeContainer):
    """IoC container."""

    sequence_factory = providers.Factory(list)


# Overriding `Container` with `OverridingContainer`:
@containers.override(Container)
class OverridingContainer(containers.DeclarativeContainer):
    """Overriding IoC container."""

    sequence_factory = providers.Factory(tuple)


# Creating some objects using overridden container:
sequence_1 = Container.sequence_factory([1, 2, 3])
sequence_2 = Container.sequence_factory([3, 2, 1])

# Making some asserts:
assert Container.overridden == (OverridingContainer,)
assert sequence_1 == (1, 2, 3) and sequence_2 == (3, 2, 1)

Also there are several useful DeclarativeContainer methods and properties that help to work with container overridings:

DynamicContainer has exactly the same functionality, except of override() decorator.