【问题标题】:Inversify's dependency injection like angular's using TS decoratorsInversify 的依赖注入,如 Angular 使用 TS 装饰器
【发布时间】:2018-08-07 08:05:57
【问题描述】:

今天我将一个 js electron 项目切换到 typescript,问自己是否有一个等价于 angular 的依赖注入。由于 Angular Universal 似乎处于非常早期的状态,并且根本没有将它与电子而不是 express 一起使用的文档,因此似乎 inversify em> 可以满足我的需要。也因为它比 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();
    }
  }

}

循环遍历提供者中的每个条目并将其绑定到反转容器对象。我想使用的这个功能如下。用法将与 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 { ...

并且应该可以以角度样式注入,例如喜欢

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

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

我不确定 inversify 的容器。它的范围仅在装饰器功能中吗?用它会不会更好

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

如何将其正确退回到AppModule?我在 servermodule 装饰器中声明类的想法是个好主意吗?

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

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

另一个想法/问题是:如果我想要除了声明和提供者之外的导入属性。那么通过装饰器修改构造函数并导入这些类会是一个好主意吗?

谢谢!

【问题讨论】:

    标签: angular typescript dependency-injection decorator inversifyjs


    【解决方案1】:

    关于半年前的这个问题,我致力于为一个看起来类似于 Angular 的分层 DI 实现装饰器函数,并将它们捆绑在 npm package 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) {}
    }
    

    注意服务。服务是在父模块中提供的,所以这是分层的。

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 2016-04-04
      相关资源
      最近更新 更多