Performance: Custom providers
Custom providers affect the dependency injection initialization time and memory usage during app startup.
providers: [{ provide: 'MY_SERVICE', useFactory: () => new Service(), inject: [] }]providers: [{ provide: 'MY_SERVICE', useFactory: () => { heavyComputation(); return new Service(); } }]| Pattern | Initialization Time | Memory Usage | Blocking Behavior | Verdict |
|---|---|---|---|---|
| Heavy synchronous factory | High | High | Blocks startup | [X] Bad |
| Lightweight factory with no heavy work | Low | Low | Non-blocking | [OK] Good |
custom provider in NestJS?useValue key to assign a fixed value to a token.useValue with a string value. Other options misuse useClass, useFactory, or useExisting which expect different types.{ provide: 'RANDOM_NUMBER', useFactory: () => Math.floor(Math.random() * 10) }
What will be the output if you inject 'RANDOM_NUMBER' twice in the same request?{ provide: 'CONFIG', useFactory: () => ({ port: 3000 }) }
If you want to inject this provider but get an error "Nest can't resolve dependencies", what is the most likely cause?providers array.useFactory with a function that returns the correct string based on process.env.NODE_ENV. { provide: 'DB_CONNECTION', useValue: process.env.NODE_ENV === 'prod' ? 'prod-db' : 'dev-db' } uses useValue which is static at module load time. Options C and D misuse useClass and useExisting with strings or conditions incorrectly.Pass the test and this pattern moves unknown