Skip to content

Commit

Permalink
Fix singleton usage
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulBGD committed Nov 15, 2021
1 parent 27e99a3 commit 7914e58
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 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.1",
"version": "0.1.2",
"author": "PaulBGD",
"license": "MIT",
"scripts": {
Expand Down
12 changes: 7 additions & 5 deletions src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ export class Container {
public register<T>(Service: Constructor<T>, instance: T) {
const serviceData: ServiceData = getServiceData(Service);

if (serviceData.singleton) {
throw new Error(`Cannot register singleton ${Service.name}`);
if (!serviceData.singleton) {
throw new Error(
`Can only register singletons, not ${Service.name}`
);
}

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

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

const all = getAllPrototypes(Service);

if (!serviceData.singleton) {
if (serviceData.singleton) {
for (const func of all) {
if (this.storage.has(func)) {
throw new Error(
Expand All @@ -76,7 +78,7 @@ export class Container {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const service = new (Service as any)();

if (!serviceData.singleton) {
if (serviceData.singleton) {
for (const func of all) {
this.storage.set(func, service);
}
Expand Down
2 changes: 1 addition & 1 deletion src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export interface ServiceData {

const SERVICE_KEY = "__service__";
export const defaultData: ServiceData = {
singleton: false,
singleton: true,
};

export function setServiceData(object: any, data: ServiceData) {
Expand Down

0 comments on commit 7914e58

Please sign in to comment.