Skip to content

Union types

This page describes support for Union types in Rodi.

  • Optional dependencies.
  • Union types dependencies.

Optional dependencies

It is uncommon for types resolved with dependency injection to have optional dependencies, however this scenario is supported by Rodi.

from rodi import Container


class A: ...


class B:
    dependency: A | None


container = Container()
container.register(A | None, A)
container.register(B)

b = container.resolve(B)
assert isinstance(b.dependency, A)

Optional types keys.

Beware that if you specify a T dependency as optional, the key type used to resolve the dependency becomes the T | None and it is not just T.

A factory function can be used to define logic that determines how the dependency must be resolved:

from rodi import Container


class A: ...


class B:
    dependency: A | None


def a_factory() -> A | None:
    # TODO: implement logic that determines what to return
    return None


container = Container()
container.add_transient_by_factory(a_factory)
container.register(B)

b = container.resolve(B)
assert b.dependency is None

Union dependencies

Union types are also supported:

from rodi import Container


class A: ...


class B: ...


class C:
    dependency: A | B


def ab_factory() -> A | B:
    # TODO: implement logic that determines what to return
    return A()


container = Container()
container.add_transient_by_factory(ab_factory)
container.register(C)

c = container.resolve(C)
assert isinstance(c.dependency, A)

Union types keys.

Beware that if you specify a union dependency such as T | U the key type used to resolve the dependency is T | U. Trying to use T or U singularly causes a CannotResolveTypeException.


The next page provides an overview of errors raised by Rodi.

Last modified on: 2025-04-17 07:04:37

RP