简体   繁体   English

在 Node.js 中注入 Typescript 依赖项的更好方法?

[英]A better way to inject Typescript dependencies in Node.js?

I'm working on a backend solution in Node.js and Express, using Typescript.我正在使用 Typescript 在 Node.js 和 Express 中开发后端解决方案。 I'm trying to do dependency injection similar to Angular, but lacking the @Injectable() decorator I'm doing this:我正在尝试进行类似于 Angular 的依赖注入,但缺少@Injectable()装饰器我正在这样做:

Dependency:依赖:

export class SomeDependency {
  public someMethod() {
    console.log('Some method is running');
  }
}

Parent:家长:

import { SomeDependency } from './someDependency';

export class Whatever {

  constructor(
    private someDependency = new SomeDependency()
  ) {}

  public doSomething() {
    console.log('Look, I\'m doing something!');
    this.someDependency.someMethod();
  }
}

It works, but it may not be the best way.它有效,但它可能不是最好的方法。 Any suggestions on how to improve it are appreciated.任何有关如何改进它的建议表示赞赏。

On the other hand, what do you guys think: is it better to import dependencies like this, in the constructor, or create new instance every time, or most of the time?另一方面,你们怎么看:像这样在构造函数中导入依赖项,还是每次或大部分时间都创建new实例更好? Like this:像这样:

import { SomeDependency } from './someDependency';

export class Whatever {

  public doSomething() {
    console.log('Look, I\'m doing something!');
    new someDependency().someMethod();
  }
}

As SomeDependency isn't a singleton, I wonder which one is less efficient: keeping an instance alive in the parent, or creating a new one every time, letting the garbage collector take care of it when the call finished.由于SomeDependency不是单例,我想知道哪个效率较低:在父级中保持一个实例处于活动状态,或者每次都创建一个新实例,让垃圾收集器在调用完成时处理它。

your use case is absolutely correct.你的用例是绝对正确的。 It is always a good practice to keep your modules as lightly coupled.保持模块轻耦合始终是一个好习惯。 So, in future you can switch between the implementation without touching the main logic but the Javascript or Typescript doesn't provide the dependency injection mechanism.因此,将来您可以在不触及主要逻辑的情况下在实现之间切换,但 Javascript 或 Typescript 不提供依赖注入机制。

To achieve this you can use a library know as Inversify.为此,您可以使用称为 Inversify 的库。

Inversify is powerful and lightweight inversion of control container for JavaScript & NodeJS. Inversify 是用于 JavaScript 和 NodeJS 的强大且轻量级的控制容器反转。 It implements IoC and allow us to inject dependencies, uncoupling our method from any implementation details它实现了 IoC 并允许我们注入依赖项,将我们的方法与任何实现细节分离

It give you the same functionality as we use in Angular like you can annotate the class with @Injectable() annotation and perform dependency injection.它为您提供与我们在 Angular 中使用的功能相同的功能,例如您可以使用 @Injectable() 注释对类进行注释并执行依赖注入。

For reference you can go to: https://www.linkedin.com/pulse/how-use-dependency-injection-nodejs-typescript-projects-ribeiro作为参考,您可以访问: https ://www.linkedin.com/pulse/how-use-dependency-injection-nodejs-typescript-projects-ribeiro

You may want to look into Dime .你可能想看看Dime It's a very simple library I made for dependency injection similar to Angular.这是我为依赖注入创建的一个非常简单的库,类似于 Angular。 There are more details on the Github page and the wiki . Github 页面wiki上有更多详细信息。 It's still in early development, so there might be bugs.它仍处于早期开发阶段,因此可能存在错误。

Example:例子:

import { ItemsService } from './items-service'; // ItemsService is an interface
import { Inject } from '@coined/dime';

class ItemsWidget {
    @Inject()
    private itemsService: ItemsService;

    render() {
        this.itemsService.getItems().subscribe(items => {
            // ...
        })
    }
}

// Setup
const appPackage = new Package("App", {
    token: "itemsService",
    provideClass: AmazonItemsService // Use any implementation
});

Dime.mountPackages(appPackage);

// Run the application
const widget = new ItemsWidget();
widget.render();

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

相关问题 在Node.js中实现更好的正则表达式的方法 - Way to implement better regex in Node.js 在node.js中有更好的方法吗? - Is there a better way to do this in node.js? Typescript / Node.js - 如何模拟传递依赖关系进行集成测试? - Typescript / Node.js - How to mock transitive dependencies for integration testing? 有没有办法从 .js 文件自动安装 node.js 依赖项? - Is there a way to automatically install node.js dependencies from a .js file? 在两个Node.js路由之间交换数据的更好方法 - Better way of exchanging data between two Node.js routes 使用 Node.js 使用 require.extensions 的更好方法 - Better way to require.extensions with Node.js 处理node.js私有模块依赖项的推荐方法是什么? - What is the recommended way to handle node.js private module dependencies? 在 GitLab CI/CD 中缓存 Node.js 依赖项的便捷方式 - Convenient way to cache Node.js dependencies in GitLab CI/CD 有没有更好的方法来处理Node.js / Expressjs中的嵌套回调? - Is there any better way to handle the nested callbacks in Node.js/Expressjs? Node.js-在回调之间管理JavaScript作用域的更好方法? - Node.js - Better way to manage javascript scopes between callbacks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM