Skip to content

Commit

Permalink
add injectAll method
Browse files Browse the repository at this point in the history
  • Loading branch information
deebloo committed Jan 30, 2025
1 parent a50ea4e commit 628c253
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
21 changes: 21 additions & 0 deletions packages/di/src/lib/injector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,24 @@ it("should allow static token to be overridden", () => {

assert.equal(res, "Hello World");
});

it("should allow you to get ALL available instances in a particular injector chain", () => {
const TOKEN = new StaticToken<string>("test");

const injector = new Injector({
providers: [[TOKEN, { factory: () => "first" }]],
parent: new Injector({
providers: [[TOKEN, { factory: () => "second" }]],
parent: new Injector({
providers: [[TOKEN, { factory: () => "third" }]],
parent: new Injector({
providers: [[TOKEN, { factory: () => "fourth" }]],
}),
}),
}),
});

const res = injector.injectAll(TOKEN);

assert.deepEqual(res, ["first", "second", "third", "fourth"]);
});
14 changes: 12 additions & 2 deletions packages/di/src/lib/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,18 @@ export class Injector {
this.providers = new Map(opts?.providers);
}

injectAll<T>(token: InjectionToken<T>, collection: T[] = []): T[] {
const result = [...collection, this.inject<T>(token, true)];

if (this.parent) {
return this.parent.injectAll(token, result);
}

return result;
}

// resolves and retuns and instance of the requested service
inject<T>(token: InjectionToken<T>): T {
inject<T>(token: InjectionToken<T>, skipParent?: boolean): T {
// check for a local instance
if (this.#instances.has(token)) {
const instance = this.#instances.get(token);
Expand Down Expand Up @@ -80,7 +90,7 @@ export class Injector {
}

// check for a parent and attempt to get there
if (this.parent) {
if (this.parent && !skipParent) {
return this.parent.inject(token);
}

Expand Down

0 comments on commit 628c253

Please sign in to comment.