Skip to content

Remove singletons when re-registering the same dependency #195

@michael-rubel

Description

@michael-rubel

Hi again @bobthemighty 👋

I have the following use case:

def client_input_closure():
    client_input: ClientInput = self.client_input_factory.create(data=body)

    self.dispatcher.dispatch(ClientInputCreated(data=client_input.model_dump()))

    return client_input

request.app.container.register(
    service=ClientInput,
    factory=client_input_closure,
    scope=Scope.singleton,
)

The attention is to scope=Scope.singleton.

If I want to have a scoped object creation (per request) without re-creating it for each service that requested the ClientInput object, I need to add the following hack:

if ClientInput in request.app.container._singletons:
    del request.app.container._singletons[ClientInput]

Making the object transient is safe, but performance will degrade depending on the application's size, as a new instance will be created for each class that requests this dependency.

I thought of overriding the register method in punq to delete the singleton if the application tries to re-register the same dependency with the singleton scope. Does this solution make sense to you or maybe this should be resolved differently?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions