Skip to content

Classes and dependency inversion principle #2800

@mapeveri

Description

@mapeveri

I have an app using hexagonal architecture and i'm trying to apply the dependency inversion principle with Depends as dependency injection. I have this:

# infraestructure/countries.py are my endpoints
@router.get('/')
async def all_countries(all_countries: AllCountries = Depends(AllCountries)) -> List[Country]:
    countries = await all_countries.handle()
    return ResponseModel(countries)
# infraestructure/mongo_country_repository.py 
# is my mongo repository to access to the collection
class MongoCountryRepository(CountryRepository, MongoBaseRepository):
    manager: DatabaseManager
    model: Country
    collection: str

    def __init__(self, manager: DatabaseManager = Depends(get_database)) -> None:
        self.manager = manager
        self.model = Country
        self.collection = 'countries'

    async def get(self, id: str) -> Country:
        return await self.get_record(id)

    async def all(self) -> List[Country]:
        return await self.get_all()

    async def create(self, record: Country) -> Country:
        return await self.insert_record(record)

And I have my application service, in another folder (not infrastructure)

# application/all_countries.py
# is my application service for get the countries
class AllCountries(Service):
    repository: CountryRepository

    def __init__(self, repository: CountryRepository) -> None:
        self.repository = repository

    async def handle(self) -> List[Country]:
        return await self.repository.all()

This example not is 100% real, because the logic is very easy, but is for demonstrate my problem.

I would like that the application service know nothing about fastapi, and I'm trying all dependencies manage to in infrastructure.
My question is how can set the repository MongoCountryRepository to AllCountries application service?. CountryRepository is an interface.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions