microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.18k stars 172 forks source link

Add support for Explicit Resource Management #230

Open RhodeHummel opened 1 year ago

RhodeHummel commented 1 year ago

Is your feature request related to a problem? Please describe. The library currently only supports disposing of objects that support the Disposable interface. However, now support for Explicit Resource Management is becoming more common and is now supported by TypeScript. It would be nice to add support for Symbol.dispose and Symbol.disposeAsync to Tsyrnge. Resource that only implement the native method of disposing of resources will not be disposed of properly by Tsyrnge and could lead to resources not being released properly.

Description In the Explicit Resource Management proposal (which is now in Stage 3), ES will now support 2 additional symbols for disposing of explicit resources Symbol.dispose and Symbol.disposeAsync.

If the Symbol.dispose or Symbol.disposeAsync are explicitly defined we should use those functions. However, as a fallback we should continue to support the legacy Dispose(): Promise<void> | void interface for legacy code.

Alternate solutions One alternative solution is to define the dispose function twice or more depending on your use case:

class TestClass implement Disposable {
  dispose(): Promise<void> {
     return this[Symbol.disposeAsync]();
  }

  [Symbol.disposeAsync]() {
    // do something here
  }
}

Additional context Sync Proposal on github (Stage 3) Async Proposal on github (Stage 3) TypeScript support (TypeScript 5.2)