CodePark/ questions / Providers & dependency injection
START PRACTICINGPRACTICE
Backend question · NestJS › Providers & dependency injection

Describe the four kinds of custom providers (useValue, useClass, useFactory, useExisting) and give a use case for each.

providers: [
  { provide: "API_KEY", useValue: "abc123" },
  { provide: PaymentGateway, useClass: process.env.NODE_ENV === "test" ? FakeGateway : StripeGateway },
  { provide: "DB", useFactory: async (cfg: ConfigService) => connect(cfg.get("DB_URL")), inject: [ConfigService] },
  { provide: "AliasedLogger", useExisting: LoggerService },
]

Each kind connects a token to something different:

  • useValue connects a token to a fixed value. Use it for a constant, a config object, or a mock in tests.
  • useClass connects a token to a class that Nest creates. Use it to choose an implementation. For example, use a fake payment gateway in tests and the real one in production. Consumers still inject the same abstract token.
  • useFactory runs a function and uses its return value. The function can depend on other providers listed in inject. It can also be async: Nest waits for the promise before it creates anything that depends on it. Use it for database connections or clients built from config.
  • useExisting creates an alias. The new token gives you the same instance as an existing provider.
  • useValue is for constants, config objects and mocks.
  • useClass chooses which implementation a token gets.
  • useFactory computes the value, can be async, and lists its dependencies in inject.
  • useExisting is an alias to an existing provider's instance.