maldoinc / wireup

Performant, concise, and easy-to-use dependency injection container for Python 3.8+.
https://maldoinc.github.io/wireup/
MIT License
97 stars 2 forks source link

Error injecting service to APIView Class #31

Closed Alireza-Tabatabaeian closed 1 month ago

Alireza-Tabatabaeian commented 1 month ago

I'm working on a django project using django rest framework

I've implemented a simple service as follows:

@service
class RegisterService:

    def random_token(self, size) -> str:
        alphabet = string.ascii_lowercase + string.digits
        return ''.join(choices(alphabet, k=size))

    def random_username(self) -> str:
        return "gu_" + self.random_token(9)

and then in views file:

class FastRegisterView(APIView):
    @container.autowire
    def __init__(self, register_service: RegisterService):
        self.register_service = register_service

    def get(self, request, username: str = None):
        username = self.get_username(username=username)
        return Response({'username': username})

    def get_username(self, username: str = None) -> str:
        if username is None:
            return self.register_service.random_username()
        return username.lower()

everytime endpoint is called it throws this error:

FastRegisterView.init() missing 1 required positional argument: 'register_service'

I'm new to wireup and I'm not sure if I am doing anything inappropriately, I also changed the class to View class to check if the problem is caused by Rest Framework but same error appeared again

maldoinc commented 1 month ago

Hi. Can you check that wireup is correctly initialized on application startup? You need to tell it where your services are so that it knows what to build.

If Django Rest Framework supports the same application/plugin system as Django then you may be able to use the Django Integration, alternatively just follow the guide in the Getting Started Docs.

Let me know if this helps.

Alireza-Tabatabaeian commented 1 month ago

Hi there thanks for your response, it was all my fault, I had a folder called services where I had initiated my services inside that where I had to put them in a package rather than folder, so after adding __init__.py file to folder everything started to work, thanks for your great package