Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Injected singleton is not a singleton #2406

Closed
ktalebian opened this issue Aug 10, 2023 · 3 comments
Closed

[BUG] Injected singleton is not a singleton #2406

ktalebian opened this issue Aug 10, 2023 · 3 comments
Assignees

Comments

@ktalebian
Copy link
Contributor

Information

  • Version: 7.34.2

I am registering a provider as a singleton. However, it is being re-initialized per injected cases.

Example

Here is the dummy class to inject. You will that I am logging whenever the constructor is called

import { Injectable, ProviderScope, registerProvider, Scope } from '@tsed/di';
import { $log } from '@tsed/common';

@Injectable()
@Scope(ProviderScope.SINGLETON)
export class Sample {
  constructor() {
    $log.info('Sample constructor');
  }

  public log() {
    $log.info('logging something');
  }
}
export const SAMPLE = Symbol.for('Sample');
// eslint-disable-next-line
export type SAMPLE = Sample;

registerProvider({
  provide: SAMPLE,
  useClass: Sample,
});

I now have two controllers where I am injecting this. I am providing one as an example:

@Controller('/')
export class IndexController {
  @Inject(SAMPLE)
  protected sample: SAMPLE;
}

When the app boots, I see

[2023-08-09T23:45:57.095] [INFO ] [TSED] - Injector created... +2ms
[2023-08-09T23:45:57.114] [INFO ] [TSED] - Build providers +19ms
[2023-08-09T23:45:57.140] [INFO ] [TSED] - MySQL connected to db xxx
[2023-08-09T23:45:57.170] [INFO ] [TSED] - Sample constructor
[2023-08-09T23:45:57.171] [INFO ] [TSED] - Sample constructor

I see TWO Sample constructor - there should only be one log.

What am I doing wrong?

@Romakita
Copy link
Collaborator

Hello @ktalebian

You example register two provider so it's totally normal to have two logs. The singleton is considered by his given token and not by his instance.

My Question is why are you trying to register the same class with the decorator and a symbol ?

See you
Romain

@github-actions
Copy link

🎉 Are you happy?

If you appreciated the support, know that it is free and is carried out on personal time ;)

A support, even a little bit makes a difference for me and continues to bring you answers!

github opencollective

@ktalebian
Copy link
Contributor Author

Ah my mistake - I misunderstood the usage. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants