Skip to content

Commit

Permalink
Class registration
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulBGD committed Nov 16, 2021
1 parent 8487129 commit 3c2cb0d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@technove/inject",
"description": "Dependency injection for TypeScript",
"version": "0.1.9",
"version": "0.1.10",
"author": "PaulBGD",
"license": "MIT",
"scripts": {
Expand Down
32 changes: 32 additions & 0 deletions src/container.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,36 @@ describe("Container", () => {

expect(val).to.be.equal(5);
});

it("uses registered instance", () => {
class A {
constructor(public val: number) {}
}

class MyClass extends A {}

const container = new Container();
container.register(A, new MyClass(5));

expect(container.get(A)).to.be.instanceOf(MyClass);
expect(container.get(A).val).to.be.equal(5);
});

it("uses registered classes", () => {
class A {
constructor(public val: number) {}
}

class MyClass extends A {
constructor() {
super(5);
}
}

const container = new Container();
container.register(MyClass);

expect(container.get(A)).to.be.instanceOf(MyClass);
expect(container.get(A).val).to.be.equal(5);
});
});
18 changes: 15 additions & 3 deletions src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { getAllPrototypes } from "./utils";
export class Container {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly storage = new Map<unknown, any>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly classes = new Map<unknown, any>();

public constructor() {
// public constructor
Expand All @@ -24,7 +26,7 @@ export class Container {
return val;
}

public register<T>(Service: Constructor<T>, instance: T) {
public register<T>(Service: Constructor<T>, instance?: T) {
const serviceData: ServiceData = getServiceData(Service);

if (!serviceData.singleton) {
Expand All @@ -43,8 +45,14 @@ export class Container {
}
}

for (const func of all) {
this.storage.set(func, instance);
if (instance) {
for (const func of all) {
this.storage.set(func, instance);
}
} else {
for (const func of all) {
this.classes.set(func, Service);
}
}
}

Expand All @@ -56,6 +64,10 @@ export class Container {
public getMaybePromise<T>(Service: Constructor<T>): T | Promise<T> {
const serviceData: ServiceData = getServiceData(Service);

if (this.classes.has(Service)) {
Service = this.classes.get(Service);
}

if (serviceData.singleton && this.storage.has(Service)) {
return this.storage.get(Service);
}
Expand Down

0 comments on commit 3c2cb0d

Please sign in to comment.