Skip to content

Disposer support #48

@jeffijoe

Description

@jeffijoe

Proposal

Support disposing dependencies.

Each resolver (registration) can specify a disposer function to call when container.dispose() is called.

Motivation

This is useful for managing dependencies that have resources to dispose—connection pools for example.

In test runners like Jest, watch-mode will recycle worker processes which means connections may or may not have been closed between each run. In testing HTTP servers, It is a good practice to call server.close() after the tests are done.

We want to be able to run cleanup on dependencies in the same way. For example:

server.on('close', () => container.dispose())

Proposed API

  • Introduce container.dispose()
  • Introduce disposer option for asClass and asFunction resolvers
  • Disposing a container also disposes it's child (scoped) containers
  • Containers are disposed bottom-first; this means scoped containers are disposed before their parent.
  • Only SCOPED and SINGLETON registrations can be disposed as they are the only ones the container caches.

Example

const pg = require('pg')
const { createContainer, asFunction } = require('awilix')
const container = createContainer()
  .register({
    pool: (
      asFunction(() => new pg.Pool({ ... }))
        .singleton()
        .disposer((pool) => pool.end())
    )
  })

// .. later, but only if a `pool` was ever created
container.dispose().then(() => {
  console.log('One disposable connection.. disposed! Huehehehe')
})

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions