Skip to content

Aliases

Roberto Prevato edited this page Oct 6, 2018 · 11 revisions

rodi supports service resolution by name and by aliases, in the following example a service UsingAlias is properly resolved, by explicitly defined aliases example and settings.

from rodi import ServiceCollection


class UsingAlias:

    def __init__(self, example, settings):
        self.example = example
        self.settings = settings


class Foo:

    def __init__(self):
        pass


class ServiceSettings:

    def __init__(self, setting_one, setting_two):
        self.setting_one = setting_one
        self.setting_two = setting_two


services = ServiceCollection()

services.add_exact_transient(UsingAlias)
services.add_exact_transient(Foo)
services.add_instance(ServiceSettings('aaa', 'bbb'))

# arrange an exact alias for UsingAlias class init parameter:
services.add_alias('example', Foo)
services.add_alias('settings', ServiceSettings)

provider = services.build_provider()
u = provider.get(UsingAlias)

assert isinstance(u, UsingAlias)
assert isinstance(u.example, Foo)
assert isinstance(u.settings, ServiceSettings)

Automatically generated aliases

When registering services, aliases are inferred by type name. Such aliases are used when type hints are missing from constructors (__init__ methods). If aliases are ambiguous, because they can refer to more than one type, an exception is thrown when building a service provider.

Disabling aliases

It is possible to disable aliases, using strict mode when instantiating a ServiceCollection:

services = ServiceCollection(strict=True)
Clone this wiki locally