Skip to content

Dependency sharing

Often, you will have dependencies that share a sub dependency. For example, you probably only want to load your configuration from enviroment variables once and then re-use the same object in multiple dependencies. In di, we call this concept dependency sharing.

How sharing works

Dependencies are usually identfied by their callable provider (see dependants for ways in which you can change this). This could be the constructor for a type or an arbitrary callable encapsulated using Depends(...). By default, dependencies are shared, but this behavior can be changed on a per-dependency basis using the share=False parameter.

from random import random

from di import Container, Dependant, Depends


def controller(
    v1: object,  # no marker is equivalent to Depends(object)
    v2: object = Depends(object),  # the default value is share=True
    v3: float = Depends(random, share=False),  # but you can set share=False
) -> None:
    assert v1 is v2
    assert v1 is not v3 and v2 is not v3


def main() -> None:
    container = Container()
    container.execute_sync(container.solve(Dependant(controller)))

Sharing and scopes

Dependencies are share within their scope and any innner scopes. Once a dependency's scope exits, it's share value is discarded and the next time the scope is entered a fresh value will be computed.