NestJs初始化顺序

huangapple go评论81阅读模式
英文:

NestJs order of initialization

问题

我正在学习NestJS,并且有一个关于NestJs初始化顺序的问题。当NestJS应用程序启动时,依赖项的创建顺序是什么?首先是模块,还是提供者,还是控制器?

我尝试阅读NestJs文档,但不够清晰。

英文:

I am studying NestJS and i have one question about the order of initialization in NestJs. When a NestJS application get bootstraped, in what order does the dependencies get created ? Module first or provider first or controller first ?

I try to read NestJs documentation but it wasn't clear enough.

答案1

得分: 1

NestJS 简单使用自顶向下的方法,解释如下:

模块初始化

当启动 NestJS 应用程序时,它首先通过初始化根模块开始,然后以递归方式初始化任何导入的模块。这意味着模块以自顶向下的方式初始化,根模块首先初始化,然后是任何导入的模块。

提供者注册

一旦所有模块都被初始化,下一步是注册提供者。提供者在每个模块内注册,它们可以在模块层次结构中被使用。提供者可以以两种方式定义 - 要么作为带有 @Injectable() 装饰器的类,要么作为值(例如字符串、数字),使用 @Inject() 装饰器。

控制器初始化

最后,在所有提供者都被注册后,控制器被初始化。控制器负责处理传入的请求并返回响应,它们可以利用提供者来处理请求逻辑。

分解

分解可以使用从你的环境变量中设置 NEST_DEBUG=true。

注意

> 你也可以使用一些钩子,例如在模块中的 onModuleInit() 方法或 onModuleInit()。

英文:

NestJS simply using top-down approach, the explaination is :

Module initialization

When a NestJS application is bootstrapped, it begins by initializing the root module, which then initializes any imported modules in a recursive manner. This means that modules are initialized in a top-down fashion, with the root module being the first to initialize, followed by any imported modules.

Provider registration

Once all the modules are initialized, the next step is to register the providers. Providers are registered within each module, and they can be used across the module hierarchy. Providers can be defined in two ways - either as a class with the @Injectable() decorator or as a value (e.g. string, number) using the @Inject() decorator.

Controller initialization

Finally, after all providers have been registered, controllers are initialized. Controllers are responsible for handling incoming requests and returning responses, and they can make use of providers to handle the request logic.

Breaking Down

breaking down you can find using NEST_DEBUG=true from your ENV variable

Note

> you can hook also such as the onModuleInit() method in modules or the
> onModuleInit()

huangapple
  • 本文由 发表于 2023年5月10日 13:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定