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

Register same Service with different injections #12

Open
pabloleonalcaide opened this issue Mar 12, 2024 · 0 comments
Open

Register same Service with different injections #12

pabloleonalcaide opened this issue Mar 12, 2024 · 0 comments

Comments

@pabloleonalcaide
Copy link

Hi!

I have been looking for a way to define two implementations for the same service at the same time (For example, SendMailService) so that one of them injects the Logger implementation FakeLogger and another of them the implementation RealLogger) with the intention of being able to take one or the other depending on the needs. However, I think we cannot build the container with the same service in duplicate (The error is that the service identified as 'SendMailService' has already been registered and you would need to "unregister it before you can register it again"
The best solution I have found would be the following:

  // SendMailService.ts
  @Service()
  export class SendMailService {
   public constructor (private readonly logger: Logger) { }
  }

  // Service Register
  diodcontainer.registerFactoryAs(
    c => {
      return new SendMailService(
        env.realImplementation
          ? c.getDependency(RealLogger)
          : c.getDependency(FakeLogger),
      );
    },
    SendMailService,
    DependencyScope.Transient,
  );
  
  // SomeController.ts
  @Controller()
  export class SomeController {
  
    public async doStuffs(): Promise<void> {
      env.realImplementation = true; // or false
      const service = container.get(SendMailService);
      await service.send();
    }
  }

Do you think there could be a better solution or that the option of taking advantage of tags that allow a dual implementation to coexist could be introduced in the future?

Example:

  diodcontainer.registerFactoryAs(
    c => {
      return new SendMailService(c.getDependency(FakeLogger));
    },
    'SendMailServiceFakeLogger',
    DependencyScope.Transient,
  );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant