-
|
Hello, In a container, I'd like to know how to getAll only already instantiated singletons. The usecase is the following: // services.ts
@injectable('Singleton')
class DB {
// ...
async close()
}
@injectable('Singleton')
class MQ {
// ...
async close()
}
@injectable('Singleton')
class SomeRepo {
constructor(@inject(DB) db: DB) {}
}// main.ts
import { DB, MQ, SomeRepo } from './services'
const services = [DB, MQ, SomeRepo]
const container = new Container()
app.on('ready', () => {
for (const service of services) {
container.bind(service).toSelf()
if (service.prototype.close) {
// See: https://github.com/inversify/monorepo/issues/1147#issuecomment-3400365381
container.bind('onClose').toResolvedValue(() => container.getAsync(service))
}
}
})
app.get('/foo', async (req, res) => {
const repo = await container.getAsync(SomeRepo)
return repo...blah()
})
// container.getAsync(MQ) ← never ever in the code
app.on('close', () => {
// Here, the container may or may not have an instance of SomeRepo and/or DB
// but never have instantiated MQ anywhere. How to retrieve the list of only
// existing singleton matching that service identifier?
const services = container.getAll<{ close: () => Promise<void> }>('onClose')
for (const service of services) {
await service.close()
}
})Thank you for your time and guidance 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
Workaround note to achieve the same effect without explicit API:
I'm marking this as answered because it's the true way of using the framework but i'm still genuinely curious on how to achieve pulling existing singleton otherwise |
Beta Was this translation helpful? Give feedback.
-
|
Hey @y-nk, as you correctly suggested, pre destroy mechanism is probably the best way to go. I wrote a plugin for this specific case you might like to consider: https://github.com/inversify/monorepo/tree/main/packages/container/libraries/plugin-dispose |
Beta Was this translation helpful? Give feedback.
Workaround note to achieve the same effect without explicit API:
@preDestroy()instead ofservice.prototype.closedetection with additional bindingcontainer.unbindAll()I'm marking this as answered because it's the true way of using the framework but i'm still genuinely curious on how to achieve pulling existing singleton otherwise