Inversify的依赖注入,就像使用TS装饰器的角度一样



今天,我将JS electon 项目切换到打字稿,问自己是否与 angular 的依赖性注入有等效。正如Angular Universal 似乎处于非常早的状态,并且根本没有文档以与Electron一起使用它而不是Emperthe Empress ,看来 inversify 可以满足我的需求。这也是因为它比角度更轻巧,因为我只需要di。

我最终试图创建一个应该类似于Angular的NgModule装饰器的装饰器。

import { app, Menu, ipcMain, BrowserWindow } from 'electron';
import { Container } from 'inversify';
import { DatabaseService } from 'core/database.service';
function servermodule(data: {providers: Array<any>}) {
  // Some code that instantiate the declarations array classes
  // Do they have to be returned, if I don't need a reference?
  let container = new Container();
  return (target: Object) => {
    for(const service of data.providers) {
      container.bind(service).toSelf();
    }
  }
}

哪个循环在提供商中的每个条目中,并将其绑定到Inversifys容器对象。我想使用的此功能如下。然后,用法将与Angulars Decorator一样。

@servermodule({
  declarations: [
    // Some other classes, that maybe can get DatabaseService injected
  ],
  providers: [
    DatabaseService
  ]
})
export class AppModule { ...

例如,DatabaseService看起来像

 import { injectable } from 'inversify';
 @injectable()
 export class DatabaseService { ...

,应以角样式注射,例如喜欢

import { inject } from 'inversify';
import { DatabaseService } from './database.service';
export class Models {
  constructor(@inject(DatabaseService) dbService: DatabaseService) { }
}

我不确定倒置容器。它的范围仅在装饰函数中吗?最好将其用作

container = new Container({ autoBindInjectable: true });

如何正确返回AppModule?我想在Server Module Decorator中声明课程的想法是一个好主意吗?

目前,我只是在TSC和电子执行上收到以下错误消息,但是没有TS绒毛错误。

App threw an error during load
Error: Cannot find module 'database.service'

另一个想法/问题是:除了声明和提供商外,我是否还要导入属性。然后,通过装饰器修改构造函数并导入这些类是一个好主意?

谢谢!

关于这个问题半年前,我致力于实现层次di的装饰函数,看起来与角度相似,并将它们捆绑在NPM软件包fl-node-di中。使用它,您可以生成模块

FlModule({
  imports: [ AnotherModule ] // imports other FlModules
  providers: [ MyService ] // adds Injectables() to the modules container
  declaration: [] // same as providers but immediatly creates an instance
  exports: [] // places the Injectable() in the parents container
})
export class MyModule {}

另一个模块看起来像

FlModule({
  declarations: [ MyComponent ]
})
export class AnotherModule {}

,组件看起来像

@Component()
export class MyComponent {
  constructor (@Inject(MyService) myService: MyService) {}
}

注意服务。该服务在父模块中提供,因此这是层次结构。

最新更新