简体   繁体   English

在没有构造函数的情况下将服务单例实例注入到另一个服务

[英]Injecting service singleton instance to another service without constructor

I have: 我有:

  • BaseService that would be used as parent class 用作父类的BaseService
  • UtilService is used for utility functions UtilService用于实用程序功能
  • AService is child class of BaseService (AService extends from BaseService) AService是BaseService的子类(AService从BaseService扩展)
  • BService is also child class of BaseService BService也是BaseService的子类

I want to inject UtilService singleton instance to BaseService but without using constructor ( constructor(baseService: BaseService){} ) because if not, both AService and BService need to pass UtilService singleton instance as argument when calling UtilService 's constructor ( super(arguments) ) which is obviously a redundant step. 我想将UtilService单例实例注入BaseService,使用构造函数(Constructor(baseService:BaseService){}),因为如果没有,则AServiceBService在调用UtilService的构造函数时都需要将UtilService单例实例作为参数传递(super(arguments) ),这显然是多余的步骤。 So I want to know if there is any another way to do this without passing UtilService singleton instance in AService/BService constructor's super call. 所以我想知道是否还有其他方法可以在AService / BService构造函数的超级调用中传递UtilService单例实例。 Thanks in advance. 提前致谢。

I don't know if it will be singelton, but you can inject a service using 我不知道会不会是辛格尔顿,但是您可以使用

constructor(private inj: Injector) { }
....where you need..
const customService= this.inj.get(CustomService)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM