0 day streak
javascript / expert
Snippet

Decoupled Service Architectures with Symbols

Using string keys for Dependency Injection (provide/inject) can lead to naming collisions. Symbols guarantee uniqueness and allow for better decoupling between the component's requirements and the actual implementation provided at the application root.

snippet.js
javascript
1
2
3
4
5
6
7
8
export const ApiServiceKey = Symbol('ApiService');
// In main.ts:
app.provide(ApiServiceKey, new RealApiService());
// In a component:
const api = inject(ApiServiceKey);
if (!api) throw new Error('ApiService not provided');
vue
Breakdown
1
export const ApiServiceKey = Symbol('ApiService');
Define a unique identifier for the service that cannot be accidentally overwritten.
2
app.provide(ApiServiceKey, ...);
Register the concrete implementation at the application level.
3
const api = inject(ApiServiceKey);
Request the dependency within any descendant component.
4
if (!api) throw new Error(...);
Ensure the service is present, providing a clear error if the injection fails.