Skip to content

container.hasInstances() or some other way to tell if instances exist without creating new ones #127

@mikl

Description

@mikl

I’ve been struggling to find a way to gracefully shut down my Node.js application after adopting TSyringe, since there appears to be no way to get existing instances without creating a new one.

Description

For example, I have a database client defined as

@singleton()
export class CassandraClient {
  // Implementation irrelevant
}

and a shutdown function (using the global container) looking like this:

  if (container.isRegistered(CassandraClient)) {
    for (const client of container.resolveAll(CassandraClient)) {
       client.shutdown())
    }
  }

…if no instances of the (singleton) CassandraClient exists, TSyringe instantiates a new one. Since I’m trying to shut down, that is counter-productive, and leads to problems trying to shut something down that hasn’t really started yet.

Solutions

I don’t really have a preference here, but I imagine one of these could solve the problem:

  1. A container.hasInstances() check that only returns true if a token has been instantiated, not just registered.
  2. A variant of (or parameter to) container.resolveAll() that only returns existing instances, instead of creating new ones.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions