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

Inversify's dependency injection like angular's using TS decorators

今天把一个js electron项目转成typescript,问自己有没有等价于angular的依赖注入。由于 Angular Universal 似乎处于非常早期的状态,并且根本没有将其与 electron 一起使用而不是 express 的文档,似乎 inversify 可以满足我的需求。也因为它比 angular 更轻量,因为我只需要 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 装饰器中的用法完全相同。

@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 { ...

并且应该可以 angular 形式注射,例如喜欢

import { inject } from 'inversify';
import { DatabaseService } from './database.service';

export class Models {
  constructor(@inject(DatabaseService) dbService: DatabaseService) { }
}

我不确定 inversify 的容器。它的作用域是否只在装饰器函数中?将它用作

会更好吗
container = new Container({ autoBindInjectable: true });

我如何return它正确地AppModule?我在服务器模块装饰器中声明 类 是个好主意吗?

现在我只收到有关 tsc 和 electron 执行的以下错误消息,但没有 ts linting 错误。

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

另一个 idea/question 是:如果我想要除了声明和提供者之外还有一个导入属性。那么通过装饰器修改构造函数并导入这些 类?

是不是一个好主意?

谢谢!

关于这个问题,半年前,我致力于为一个看起来类似于angular的分层DI实现装饰器函数,并将它们捆绑在一个npm package fl-node-di中。有了它你就可以生成 modules

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) {}
}

关注服务。该服务在父模块中提供,因此是分层的。