-
Notifications
You must be signed in to change notification settings - Fork 18
Examples
Roberto Prevato edited this page Oct 6, 2018
·
11 revisions
Consider the example below:
from abc import ABC, abstractmethod
# domain object:
class Cat:
def __init__(self, name):
self.name = name
# abstract interface
class ICatsRepository(ABC):
@abstractmethod
def get_by_id(self, _id) -> Cat:
pass
# one of the possible implementations of ICatsRepository
class InMemoryCatsRepository(ICatsRepository):
def __init__(self):
self._cats = {}
def get_by_id(self, _id) -> Cat:
return self._cats.get(_id)
# NB: example of business layer class, using interface of repository
class GetCatRequestHandler:
def __init__(self, cats_repository: ICatsRepository):
self.repo = cats_repository
rodi
configuration to obtain instances of GetCatRequestHandler
would look like this:
# (imports omitted...)
from rodi import ServiceCollection
services = ServiceCollection()
# configuring services...
services.add_transient(ICatsRepository, InMemoryCatsRepository)
services.add_exact_transient(GetCatRequestHandler)
# building the provider
provider = services.build_provider()
# obtaining instances of services:
get_cat_handler = provider.get(GetCatRequestHandler)
assert isinstance(get_cat_handler, GetCatRequestHandler)
assert isinstance(get_cat_handler.repo, InMemoryCatsRepository)
In this example, type resolution happens by parameter name, when requiring Foo
service, a new one is instantiated passing the configured singleton of Settings
to its constructor.
class Foo:
def __init__(self, settings):
self.settings = settings
class Settings:
def __init__(self, db_connection_string):
self.db_connection_string = db_connection_string
# in some other module..
from rodi import ServiceCollection
services = ServiceCollection()
# configuring services...
services.add_instance(Settings("whatever/connection/string"))
services.add_exact_transient(Foo)
# building the provider
provider = services.build_provider()
# obtaining instances of services:
foo = provider.get(Foo)
assert isinstance(foo, Foo)
assert isinstance(foo.settings, Settings)
Please look at tests code, for more examples.