or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-tsyringe

Lightweight dependency injection container for JavaScript/TypeScript

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/tsyringe@4.10.x

To install, run

npx @tessl/cli install tessl/npm-tsyringe@4.10.0

0

# TSyringe

1

2

TSyringe is a lightweight dependency injection container for TypeScript/JavaScript that enables constructor injection for building modular, testable applications. It provides comprehensive decorators for marking classes and parameters, supports multiple provider types for flexible service registration, and offers advanced features like scoped lifecycles, child containers, and interception hooks.

3

4

## Package Information

5

6

- **Package Name**: tsyringe

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install tsyringe reflect-metadata`

10

11

## Core Imports

12

13

```typescript

14

import "reflect-metadata"; // Required polyfill

15

import { container, injectable, singleton, inject } from "tsyringe";

16

```

17

18

For CommonJS:

19

20

```javascript

21

require("reflect-metadata");

22

const { container, injectable, singleton, inject } = require("tsyringe");

23

```

24

25

**Note**: TSyringe requires the `reflect-metadata` polyfill to be imported at the top of your entry point.

26

27

## Basic Usage

28

29

```typescript

30

import "reflect-metadata";

31

import { container, injectable, singleton, inject } from "tsyringe";

32

33

// Define services

34

@injectable()

35

class Logger {

36

log(message: string) {

37

console.log(message);

38

}

39

}

40

41

@injectable()

42

class UserService {

43

constructor(private logger: Logger) {}

44

45

getUser(id: string) {

46

this.logger.log(`Getting user ${id}`);

47

return { id, name: "John Doe" };

48

}

49

}

50

51

// Register and resolve

52

container.register("UserService", UserService);

53

const userService = container.resolve<UserService>("UserService");

54

const user = userService.getUser("123");

55

```

56

57

## Architecture

58

59

TSyringe is built around several key components:

60

61

- **Dependency Container**: Core container interface for registration and resolution with hierarchical child container support

62

- **Decorator System**: Comprehensive decorators (@injectable, @singleton, @inject, etc.) for marking classes and dependencies

63

- **Provider System**: Flexible provider types (class, value, factory, token) for different dependency registration patterns

64

- **Lifecycle Management**: Multiple lifecycle scopes (transient, singleton, container-scoped, resolution-scoped)

65

- **Lazy Loading**: DelayedConstructor and delay utilities for lazy dependency initialization

66

- **Interception**: Pre/post resolution hooks for advanced dependency customization

67

68

## Capabilities

69

70

### Dependency Container

71

72

Core container interface providing dependency registration, resolution, and lifecycle management. Supports hierarchical child containers and disposal patterns.

73

74

```typescript { .api }

75

interface DependencyContainer extends Disposable {

76

// Registration methods (overloaded)

77

register<T>(token: InjectionToken<T>, provider: Provider<T>, options?: RegistrationOptions): DependencyContainer;

78

79

// Singleton registration

80

registerSingleton<T>(from: InjectionToken<T>, to: InjectionToken<T>): DependencyContainer;

81

registerSingleton<T>(token: constructor<T>): DependencyContainer;

82

83

// Type registration

84

registerType<T>(from: InjectionToken<T>, to: InjectionToken<T>): DependencyContainer;

85

86

// Instance registration

87

registerInstance<T>(token: InjectionToken<T>, instance: T): DependencyContainer;

88

89

// Resolution methods

90

resolve<T>(token: InjectionToken<T>): T;

91

resolveAll<T>(token: InjectionToken<T>): T[];

92

93

// Registration check

94

isRegistered<T>(token: InjectionToken<T>, recursive?: boolean): boolean;

95

96

// Container management

97

reset(): void;

98

clearInstances(): void;

99

createChildContainer(): DependencyContainer;

100

101

// Interception

102

beforeResolution<T>(

103

token: InjectionToken<T>,

104

callback: PreResolutionInterceptorCallback<T>,

105

options?: InterceptorOptions

106

): void;

107

afterResolution<T>(

108

token: InjectionToken<T>,

109

callback: PostResolutionInterceptorCallback<T>,

110

options?: InterceptorOptions

111

): void;

112

}

113

114

// Global container instance

115

const container: DependencyContainer;

116

```

117

118

[Dependency Container](./dependency-container.md)

119

120

### Class Decorators

121

122

Decorators for marking classes as injectable, defining lifecycle behavior, and configuring automatic registration.

123

124

```typescript { .api }

125

function injectable<T>(options?: {token?: InjectionToken<T> | InjectionToken<T>[]}): ClassDecorator;

126

function singleton<T>(): ClassDecorator;

127

function scoped<T>(lifecycle: Lifecycle.ContainerScoped | Lifecycle.ResolutionScoped, token?: InjectionToken<T>): ClassDecorator;

128

function autoInjectable(): ClassDecorator;

129

function registry(registrations: ({token: InjectionToken; options?: RegistrationOptions} & Provider<any>)[]): ClassDecorator;

130

```

131

132

[Decorators](./decorators.md)

133

134

### Parameter Decorators

135

136

Decorators for parameter-level dependency injection, enabling fine-grained control over individual constructor and method parameters.

137

138

```typescript { .api }

139

function inject(token: InjectionToken<any>, options?: {isOptional?: boolean}): ParameterDecorator;

140

function injectAll(token: InjectionToken<any>, options?: {isOptional?: boolean}): ParameterDecorator;

141

function injectWithTransform(

142

token: InjectionToken<any>,

143

transformer: InjectionToken<Transform<any, any>>,

144

...args: any[]

145

): ParameterDecorator;

146

function injectAllWithTransform(

147

token: InjectionToken<any>,

148

transformer: InjectionToken<Transform<[any], any>>,

149

...args: any[]

150

): ParameterDecorator;

151

```

152

153

### Provider System

154

155

Flexible provider types for registering dependencies using different patterns (class constructors, factory functions, concrete values, or token aliases).

156

157

```typescript { .api }

158

type Provider<T> = ClassProvider<T> | FactoryProvider<T> | ValueProvider<T> | TokenProvider<T>;

159

160

interface ClassProvider<T> {

161

useClass: constructor<T> | DelayedConstructor<T>;

162

}

163

164

interface FactoryProvider<T> {

165

useFactory: (dependencyContainer: DependencyContainer) => T;

166

}

167

168

interface ValueProvider<T> {

169

useValue: T;

170

}

171

172

interface TokenProvider<T> {

173

useToken: InjectionToken<T>;

174

}

175

```

176

177

[Provider System](./providers.md)

178

179

### Lifecycle Management

180

181

Comprehensive lifecycle management with multiple scopes, registration options, and disposable resource handling.

182

183

```typescript { .api }

184

enum Lifecycle {

185

Transient = 0,

186

Singleton = 1,

187

ResolutionScoped = 2,

188

ContainerScoped = 3

189

}

190

191

interface RegistrationOptions {

192

lifecycle: Lifecycle;

193

}

194

195

interface Disposable {

196

dispose(): Promise<void> | void;

197

}

198

```

199

200

[Lifecycle Management](./lifecycle-management.md)

201

202

### Factory Functions

203

204

Advanced factory utilities for caching strategies and conditional instantiation patterns.

205

206

```typescript { .api }

207

type FactoryFunction<T> = (dependencyContainer: DependencyContainer) => T;

208

209

function instanceCachingFactory<T>(factoryFunc: FactoryFunction<T>): FactoryFunction<T>;

210

function instancePerContainerCachingFactory<T>(factoryFunc: FactoryFunction<T>): FactoryFunction<T>;

211

function predicateAwareClassFactory<T>(

212

predicate: (dependencyContainer: DependencyContainer) => boolean,

213

trueConstructor: constructor<T>,

214

falseConstructor: constructor<T>,

215

useCaching?: boolean

216

): FactoryFunction<T>;

217

```

218

219

[Factory Functions](./factories.md)

220

221

### Lazy Loading

222

223

Lazy initialization utilities for circular dependency resolution and delayed constructor instantiation.

224

225

```typescript { .api }

226

function delay<T>(wrappedConstructor: () => constructor<T>): DelayedConstructor<T>;

227

228

class DelayedConstructor<T> {

229

createProxy(createObject: (ctor: constructor<T>) => T): T;

230

}

231

```

232

233

[Lazy Loading](./lazy-loading.md)

234

235

## Types

236

237

```typescript { .api }

238

// Core injection token type

239

type InjectionToken<T> = constructor<T> | string | symbol | DelayedConstructor<T>;

240

241

// Constructor function type

242

type constructor<T> = {new (...args: any[]): T};

243

244

// Frequency for interceptors

245

type Frequency = "Always" | "Once";

246

247

// Resolution types

248

type ResolutionType = "Single" | "All";

249

250

// Interceptor callback types

251

type PreResolutionInterceptorCallback<T> = (

252

token: InjectionToken<T>,

253

resolutionType: ResolutionType

254

) => void;

255

256

type PostResolutionInterceptorCallback<T> = (

257

token: InjectionToken<T>,

258

result: T | T[],

259

resolutionType: ResolutionType

260

) => void;

261

262

// Interceptor options

263

interface InterceptorOptions {

264

frequency: Frequency;

265

}

266

267

// Transform interface for dependency transformation

268

interface Transform<TIn, TOut> {

269

transform: (incoming: TIn, ...args: any[]) => TOut;

270

}

271

272

// Factory function type

273

type FactoryFunction<T> = (dependencyContainer: DependencyContainer) => T;

274

```