You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/fundamentals/dependency-injection.md
+79Lines changed: 79 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -208,6 +208,85 @@ export class CatsRepository {
208
208
209
209
While we directly use the string `'CONNECTION'` in the above examples for illustration purposes, for clean code organization, it's best practice to define tokens in a separate file, such as `constants.ts`. Treat them much as you would symbols or enums that are defined in their own file and imported where needed.
210
210
211
+
#### Interfaces and abstract classes
212
+
213
+
TypeScript types/interfaces are erased during compilation, so Nest can't reference them at runtime. This means an interface can describe the shape of a dependency, but it can't be used as a DI token by itself.
214
+
215
+
Since Nest resolves providers by runtime tokens, use a string or `Symbol` token when registering a provider for an interface:
Use string or `Symbol` tokens when the runtime DI token should be decoupled from a class artifact. `Symbol` tokens are especially useful for libraries and larger applications because each symbol has a unique runtime identity, which helps avoid accidental collisions that can occur when unrelated providers use the same string token. When using a symbol token, export it from a shared file and reuse the same symbol instance wherever the provider is registered and injected. Use abstract classes when one artifact should act as both the contract and the runtime token, and you prefer simpler constructor injection. A plain interface is still a good choice when the type is only used for compile-time checking and no DI token is needed.
289
+
211
290
#### Class providers: `useClass`
212
291
213
292
The `useClass` syntax allows you to dynamically determine a class that a token should resolve to. For example, suppose we have an abstract (or default) `ConfigService` class. Depending on the current environment, we want Nest to provide a different implementation of the configuration service. The following code implements such a strategy.
0 commit comments