【问题标题】:Is there any way I can Inject my Service class in a non Service annotated classes in NodeJs?有什么方法可以将我的服务类注入 NodeJs 中的非服务注释类中?
【发布时间】:2021-01-04 16:04:48
【问题描述】:

这个 ABCService 类在服务启动时执行一些初始化

class ABCService {
     
   public init() : void {
     some stuff...
    }
export const service = new ABCService();

我正在使用这个类作为加载器

import { MicroframeworkLoader, MicroframeworkSettings } from 'microframework-w3tec';
import { service } from '../ABCService';
export const serviceLoader: MicroframeworkLoader = (settings: MicroframeworkSettings | undefined) => {
    service.init();
};

我在 APP.ts 文件的 bootstrapMicroframework 加载器中使用这个 serviceLoader。

bootstrapMicroframework({
   
    loaders: [
        serviceLoader
    ],
}).then(() => ... )
.catch(error => log.error('Application is crashed: ' + error));

现在我有了另一个使用@Service 注释的服务类

@Service()
export public class XYZService {

 constructor(private userRepository: UserRepository, private dependency2: Dependency2){
  
  }
    
   public doSomeThing(): Promise<any> {
     ....
     ....
   }
  }

我想在 ABCService 中注入这个 XYZService 类,而 XYZService 中的所有依赖项都由容器注入。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript node.js typescript dependency-injection


    【解决方案1】:

    我知道使用 typedi 可以在非服务类中获取服务类的实例

    Container.get<ServiceClassType>(ServiceClassType);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多