Skip to content

Examples

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

Type resolution by type hints inside constructors

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:

# (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)
Clone this wiki locally