philipokiokio / FastAPI_SAAS_Template

FastAPI SAAS Template (Boilerplate code)
148 stars 21 forks source link

Use DI instead of initializing a concrete class and then inject it in another class #3

Closed evilvodun closed 1 year ago

evilvodun commented 1 year ago

I see on services class there are concrete classes injected, I think can be used Dependency injection to inject something in constructor. I can do that and I can open a PR For example this code:

  def __init__(self):
        # intializing repository
        self.org_repo = org_repo
        self.org_member_repo = org_member_repo

The classes: org_repo and org_member_repo should be injected as dependencies

philipokiokio commented 1 year ago

Hi chief. So I just did a read-up on DI and I get it however I don't see the reason for it, can you explain it to me?

Here is why at the highest level it ends up using the Depends that ships natively with FastAPI.

The Aim of the template is also reusability and extensibility as such I would like every irrespective of technical ability to be able to understand the length and breadth of the application.

what do you think?

evilvodun commented 1 year ago

My idea was in this case mostly for readability reasons for example:

class ContactService:
    contact_store: ContactStore

    def __init__(self, contact_store: ContactStore = Depends()) -> None:
        self.contact_store = contact_store

And doing so, we do not need to initialize every time every class But it is good as it is right now in your code.