0
# Dependency Container
1
2
Core container interface providing comprehensive dependency registration, resolution, and lifecycle management with support for hierarchical child containers and resource disposal.
3
4
## Capabilities
5
6
### Global Container Instance
7
8
Pre-configured global container instance ready for immediate use.
9
10
```typescript { .api }
11
/**
12
* Global dependency container instance
13
* Pre-created container available for immediate dependency registration and resolution
14
*/
15
const container: DependencyContainer;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { container } from "tsyringe";
22
23
// Register dependencies
24
container.register("ApiUrl", { useValue: "https://api.example.com" });
25
container.registerSingleton(DatabaseService);
26
27
// Resolve dependencies
28
const apiUrl = container.resolve<string>("ApiUrl");
29
const dbService = container.resolve(DatabaseService);
30
```
31
32
### Registration Methods
33
34
Register dependencies using various provider types and configuration options.
35
36
```typescript { .api }
37
/**
38
* Register a dependency with flexible provider options
39
* Multiple overloads support different provider types
40
*/
41
register<T>(token: InjectionToken<T>, provider: ValueProvider<T>): DependencyContainer;
42
register<T>(token: InjectionToken<T>, provider: FactoryProvider<T>): DependencyContainer;
43
register<T>(token: InjectionToken<T>, provider: TokenProvider<T>, options?: RegistrationOptions): DependencyContainer;
44
register<T>(token: InjectionToken<T>, provider: ClassProvider<T>, options?: RegistrationOptions): DependencyContainer;
45
register<T>(token: InjectionToken<T>, provider: constructor<T>, options?: RegistrationOptions): DependencyContainer;
46
47
/**
48
* Register a singleton dependency (shared instance across container)
49
*/
50
registerSingleton<T>(from: InjectionToken<T>, to: constructor<T>): DependencyContainer;
51
registerSingleton<T>(token: constructor<T>): DependencyContainer;
52
53
/**
54
* Register a type mapping (alias one token to another)
55
*/
56
registerType<T>(from: InjectionToken<T>, to: InjectionToken<T>): DependencyContainer;
57
58
/**
59
* Register a concrete instance directly
60
*/
61
registerInstance<T>(token: InjectionToken<T>, instance: T): DependencyContainer;
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
// Value provider
68
container.register("config", { useValue: { apiUrl: "https://api.com" } });
69
70
// Factory provider
71
container.register("logger", {
72
useFactory: (c) => new Logger(c.resolve("config"))
73
});
74
75
// Class provider
76
container.register("UserService", UserService, { lifecycle: Lifecycle.Singleton });
77
78
// Constructor shorthand
79
container.register("UserService", UserService);
80
81
// Singleton registration
82
container.registerSingleton(DatabaseService);
83
container.registerSingleton("IUserRepo", UserRepository);
84
85
// Type mapping
86
container.registerType("ILogger", "ConsoleLogger");
87
88
// Instance registration
89
container.registerInstance("startTime", new Date());
90
```
91
92
### Resolution Methods
93
94
Resolve registered dependencies with single or multiple instance support.
95
96
```typescript { .api }
97
/**
98
* Resolve a single instance of the registered dependency
99
* @param token - The injection token to resolve
100
* @returns Resolved instance of type T
101
*/
102
resolve<T>(token: InjectionToken<T>): T;
103
104
/**
105
* Resolve all registered instances for a token (useful for plugin patterns)
106
* @param token - The injection token to resolve all instances for
107
* @returns Array of all resolved instances
108
*/
109
resolveAll<T>(token: InjectionToken<T>): T[];
110
```
111
112
**Usage Examples:**
113
114
```typescript
115
// Single resolution
116
const userService = container.resolve<UserService>("UserService");
117
const logger = container.resolve(Logger);
118
119
// Multiple resolution (all registered instances)
120
const plugins = container.resolveAll<Plugin>("Plugin");
121
const validators = container.resolveAll<Validator>("Validator");
122
```
123
124
### Container Management
125
126
Create child containers and manage container hierarchy for scoped dependency management.
127
128
```typescript { .api }
129
/**
130
* Create a child container that inherits from this container
131
* Child containers can override parent registrations
132
* @returns New child DependencyContainer instance
133
*/
134
createChildContainer(): DependencyContainer;
135
136
/**
137
* Check if a token is registered in this container
138
* @param token - Token to check registration for
139
* @param recursive - Whether to check parent containers (default: true)
140
* @returns True if token is registered
141
*/
142
isRegistered<T>(token: InjectionToken<T>, recursive?: boolean): boolean;
143
144
/**
145
* Clear all registrations from this container
146
* Does not affect parent containers
147
*/
148
reset(): void;
149
150
/**
151
* Clear all cached instances but keep registrations
152
* Forces fresh instance creation on next resolve
153
*/
154
clearInstances(): void;
155
```
156
157
**Usage Examples:**
158
159
```typescript
160
// Child container usage
161
const childContainer = container.createChildContainer();
162
childContainer.register("ChildService", ChildService);
163
164
const hasService = childContainer.isRegistered("UserService"); // true (inherited)
165
const hasChild = container.isRegistered("ChildService"); // false (child-only)
166
167
// Container management
168
container.reset(); // Clear all registrations
169
container.clearInstances(); // Clear cached instances only
170
```
171
172
### Interception Hooks
173
174
Register callbacks for pre and post resolution interception to customize dependency behavior.
175
176
```typescript { .api }
177
/**
178
* Register a callback to execute before dependency resolution
179
* @param token - Token to intercept
180
* @param callback - Callback function to execute
181
* @param options - Interception options
182
*/
183
beforeResolution<T>(
184
token: InjectionToken<T>,
185
callback: PreResolutionInterceptorCallback<T>,
186
options?: InterceptorOptions
187
): void;
188
189
/**
190
* Register a callback to execute after dependency resolution
191
* @param token - Token to intercept
192
* @param callback - Callback function to execute
193
* @param options - Interception options
194
*/
195
afterResolution<T>(
196
token: InjectionToken<T>,
197
callback: PostResolutionInterceptorCallback<T>,
198
options?: InterceptorOptions
199
): void;
200
```
201
202
**Usage Examples:**
203
204
```typescript
205
// Logging interceptor
206
container.beforeResolution("UserService", (token, resolutionType) => {
207
console.log(`Resolving ${String(token)} as ${resolutionType}`);
208
});
209
210
container.afterResolution("UserService", (token, result, resolutionType) => {
211
console.log(`Resolved ${String(token)}: ${result}`);
212
});
213
214
// One-time interceptor
215
container.afterResolution(
216
"DatabaseService",
217
(token, result) => console.log("Database connected"),
218
{ frequency: "Once" }
219
);
220
```
221
222
### Resource Disposal
223
224
Dispose the container and all registered disposable resources.
225
226
```typescript { .api }
227
/**
228
* Dispose the container and all registered disposable resources
229
* Calls dispose() on all instances that implement Disposable interface
230
* @returns Promise that resolves when all disposals complete
231
*/
232
dispose(): Promise<void>;
233
```
234
235
**Usage Examples:**
236
237
```typescript
238
// Proper cleanup
239
class DatabaseService implements Disposable {
240
async dispose() {
241
await this.connection.close();
242
}
243
}
244
245
container.registerSingleton(DatabaseService);
246
247
// Later, cleanup all resources
248
await container.dispose();
249
```
250
251
## Types
252
253
```typescript { .api }
254
// Main container interface
255
interface DependencyContainer extends Disposable {
256
register<T>(token: InjectionToken<T>, provider: Provider<T>, options?: RegistrationOptions): DependencyContainer;
257
registerSingleton<T>(from: InjectionToken<T>, to?: constructor<T>): DependencyContainer;
258
registerType<T>(from: InjectionToken<T>, to: InjectionToken<T>): DependencyContainer;
259
registerInstance<T>(token: InjectionToken<T>, instance: T): DependencyContainer;
260
resolve<T>(token: InjectionToken<T>): T;
261
resolveAll<T>(token: InjectionToken<T>): T[];
262
isRegistered<T>(token: InjectionToken<T>, recursive?: boolean): boolean;
263
reset(): void;
264
clearInstances(): void;
265
createChildContainer(): DependencyContainer;
266
beforeResolution<T>(token: InjectionToken<T>, callback: PreResolutionInterceptorCallback<T>, options?: InterceptorOptions): void;
267
afterResolution<T>(token: InjectionToken<T>, callback: PostResolutionInterceptorCallback<T>, options?: InterceptorOptions): void;
268
dispose(): Promise<void>;
269
}
270
271
// Interceptor options
272
interface InterceptorOptions {
273
frequency: Frequency;
274
}
275
276
// Callback types
277
type PreResolutionInterceptorCallback<T> = (token: InjectionToken<T>, resolutionType: ResolutionType) => void;
278
type PostResolutionInterceptorCallback<T> = (token: InjectionToken<T>, result: T | T[], resolutionType: ResolutionType) => void;
279
```