blubber / django_injector

Dependency injection in Django.
BSD 2-Clause "Simplified" License
49 stars 7 forks source link

Scope for apps #18

Closed LEv145 closed 6 months ago

LEv145 commented 2 years ago

I haven't found how to do dependency injection for a specific application, it can only be done globally, it would be convenient to add scope for a specific django apps:

class PollsClientModule(Module):
     @app("polls")
     @singleton
     @provider
     def provide_client(self) -> ABCMyClient:
           ...

class CatsClientModule(Module):
     @app("cats")
     @singleton
     @provider
     def provide_client(self) -> ABCMyClient:
           ...

polls/views.py:

def index_view(request: HttpRequest, client: ABCMyClient) -> HttpResponse:  # ABCMyClient from PollsClientModule
    ...

cats/views.py:

def index_view(request: HttpRequest, client: ABCMyClient) -> HttpResponse:  # ABCMyClient from CatsClientModule
    ...
blubber commented 2 years ago

If I understand you correctly you want to bind an instance of a service to a specific app, such that all calls within the context of that app are services by a single instance during the lifetime of the app?

I think this can be done to some extend, but I'm not sure it's a good idea. The problem is that for some calls it is possible to determine what app the function that receives the service belongs to. For instance in case of a view function, the request instance has an attribute that specifies the app that the route belongs to if I remember correctly. However, other, non-Django, functions do not have this information. This makes it nearly impossible to reliably determine the app that a particular function belongs to.

Can I ask why you want this feature?

LEv145 commented 2 years ago

polls/views.py:

def index_view(request: HttpRequest, client: DiscordClient) -> HttpResponse:  #  client is PollsDiscordClient()
    ...

cats/views.py:

def index_view(request: HttpRequest, client: DiscordClient) -> HttpResponse:  # client is CatsDiscordClient()
    ...

How can I transfer different objects to different applications without this? (The problem will be even greater if the applications are obtained from a repository that other people make) I think this can be solved through scope

blubber commented 2 years ago

I don't understand the problem you're referring to. Can you explain in more detail what the problem is with the snippet you've posted?