molszanski / iti

~1kB Dependency Injection Library for Typescript and React with a unique support of async flow
https://itijs.org
MIT License
129 stars 6 forks source link

add disposing feature. `addDisposer` and `disposerAll` methods #26

Closed molszanski closed 1 year ago

molszanski commented 1 year ago

Related to a conversation with @moltar https://github.com/molszanski/iti/issues/21

Propblem

class DatabaseConnection {
  disconnect(): Promise<void> {
    // ... disconnect
  }
}

let node = makeRoot()
  .add({
    db: () => new DatabaseConnection(),
  })
  .dispose({
    db: (containers) => containers.db.disconnect(),
  })

// disposes of for all resources that have it defined
await node.dispose()

// under the hood (internals)
class Node {
  async dispose(): Promise<void> {
    await Promise.all(this.getDisposableResources().map((r) => r()))
  }
}