NestJS跨模块覆盖Provider失效:注入原实现而非新实现求助
问题描述
尝试在NestJS中通过自定义Provider用新实现覆盖原服务,但注入的仍是原服务实现,页面显示"Hello World"而非预期的"NEW SERVICE"。相关代码如下:
other-module.ts
@Module({ imports: [], controllers: [AppController], providers: [AppService], exports: [AppService] }) export class OtherModule {}
app.module.ts
class NewService extends AppService { getHello(): string { return 'NEW SERVICE'; } } @Module({ imports: [OtherModule], controllers: [], providers: [ { provide: AppService, useClass: NewService, }, ], }) export class AppModule {}
问题原因
AppController属于OtherModule,根据NestJS的模块作用域规则,模块内的控制器会优先使用当前模块提供的依赖实例,不会去父模块(AppModule)查找覆盖后的实现。因此AppController注入的是OtherModule自身实例化的AppService,而非AppModule中配置的NewService。
解决方案
提供两种可行的修改方案:
方案一:将控制器迁移至AppModule
把AppController从OtherModule移到AppModule,让控制器使用AppModule中配置的自定义Provider:
修改other-module.ts:
@Module({ imports: [], controllers: [], // 移除AppController providers: [AppService], exports: [AppService] }) export class OtherModule {}
修改app.module.ts:
class NewService extends AppService { getHello(): string { return 'NEW SERVICE'; } } @Module({ imports: [OtherModule], controllers: [AppController], // 添加AppController providers: [ { provide: AppService, useClass: NewService, }, ], }) export class AppModule {}
方案二:在OtherModule内直接覆盖服务实现
如果需要保留AppController在OtherModule中,直接在该模块内部配置自定义Provider:
修改other-module.ts:
class NewService extends AppService { getHello(): string { return 'NEW SERVICE'; } } @Module({ imports: [], controllers: [AppController], providers: [ { provide: AppService, useClass: NewService, }, ], exports: [AppService] }) export class OtherModule {}
内容的提问来源于stack exchange,提问作者Rafael Cerávolo
相关产品推荐
相关产品推荐

