-
Notifications
You must be signed in to change notification settings - Fork 18
Aliases
Roberto Prevato edited this page Jan 31, 2021
·
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 Container
class UsingAlias:
def __init__(self, example, settings):
self.example = example
self.settings = settings
class Foo:
def __init__(self):
pass
class ContainerSettings:
def __init__(self, setting_one, setting_two):
self.setting_one = setting_one
self.setting_two = setting_two
container = Container()
container.add_exact_transient(UsingAlias)
container.add_exact_transient(Foo)
container.add_instance(ContainerSettings('aaa', 'bbb'))
# arrange an exact alias for UsingAlias class init parameter:
container.add_alias('example', Foo)
container.add_alias('settings', ContainerSettings)
services = container.build_provider()
u = services.get(UsingAlias)
assert isinstance(u, UsingAlias)
assert isinstance(u.example, Foo)
assert isinstance(u.settings, ContainerSettings)
When registering container, 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 services.
Example of inferred aliases:
Type name | Aliases |
---|---|
CatsRepository | cats_repository, CatsRepository, catsrepository |
ICatsRepository | icats_repository, ICatsRepository, icatsrepository |
HTTPContext | http_context, HTTPContext, httpcontext |
Foo | foo, Foo |
rodi
also supports to define exact aliases, that take precedence over inferred ones.
container.set_alias('example', ExampleType)
It is possible to disable aliases, using strict
mode when instantiating a Container:
container = Container(strict=True)