BlackSheep icon indicating copy to clipboard operation
BlackSheep copied to clipboard

Interface for Application.services

Open IlyaBulatau opened this issue 7 months ago • 2 comments

When i access the Application.services i get the Container object, but my IDE does not suggest object methods since the typing specifies the ContainerProtocol. I understand that this object is in the rodi, but is it possible to add an interface that extends the ContainerProtocol with all methods from the Container?

IlyaBulatau avatar May 15 '25 16:05 IlyaBulatau

Hi, The ContainerProtocol was added especially to support replacing Rodi with other kinds of DI containers. I recently prepared examples to illustrate how to use Dependency Injector instead of my own library, and added details to the documentation.

To resolve the issue with IDE suggestions, I would recommend a combination of these options:

  • Using assert isinstance(app.services, rodi.Container) where necessary. The IDE should give you the right hints, and when you run your application for production you can disable assertions so that they don't affect performance.

Image

  • Subclassing Application to define your own version of the application, specifying that services is of the specific type.
from blacksheep import Application
from rodi import Container

class MyApplication(Application):
    services: Container

Image

  • Configuring your DI container before attaching it to your application. This is the approach I personally prefer in my private projects, because I can configure the container in Python packages that are abstracted from the front-end layer. For instance, here I am configuring concrete implementations of data access logic using SQL, and here an alternative implementation that uses Azure Storage Table API. Then by application settings, I can use the SQL persistence layer or the Table API persistence layer simply by wiring the right classes.

RobertoPrevato avatar May 16 '25 20:05 RobertoPrevato

Okay, thanks for the clarifications and code examples.

IlyaBulatau avatar May 17 '25 04:05 IlyaBulatau