nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
456 stars 23 forks source link

Disposed children retained by parent #37

Closed tynor closed 3 years ago

tynor commented 3 years ago

Hello,

First of all, I really like the premise and API of this package.

The pattern I use DI for is to have a base container for the application, then create a child container for a transaction, so all of those values will share the transaction state (current HTTP request, session, DB transaction, etc).

One thing I noticed when looking at the code, it seems like children are only removed from the childInjectors array when their parent is disposed.

Is this behavior intentional? It seems like it would make the injector used to create each transaction injector "collect" children as the program executes until memory is exhausted.

This little demo script demonstrates the behavior. I would expect an output of 0, but instead get 2.

import { createInjector } from 'typed-inject';

const root = createInjector();
[root.provideValue('a', 'a'), root.provideValue('a', 'a')]
  .reduce((p, x) => p.then(() => x.dispose()), Promise.resolve())
  .then(() => {
    console.log((root as any).childInjectors.length);
  });
nicojs commented 3 years ago

Hmm good point. I think it makes sense for disposed children to be removed from their respective parent.

I'd be happy to accept a PR for this.

aleclofabbro commented 3 years ago

The pattern I use DI for is to have a base container for the application, then create a child container for a transaction, so all of those values will share the transaction state (current HTTP request, session, DB transaction, etc).

Hi @tynor , this pattern is intriguing, I would grateful to you explaining it a bit more or sharing a snippet showing it :) !