Replace manual class instantiation in a TypeScript app with a container that automatically creates and injects dependencies
Make TypeScript services easier to unit test by swapping real implementations for mocks in the container
Enforce singleton instances of shared services like a database connection so only one instance ever exists
Use child containers to scope dependencies to a specific request or operation lifecycle in a server app
Requires enabling experimentalDecorators and emitDecoratorMetadata in tsconfig.json plus a Reflect polyfill, neither is on by default in TypeScript.
TSyringe is a lightweight library from Microsoft that handles dependency injection for TypeScript and JavaScript applications. Dependency injection is a pattern where a class declares what other objects it needs, and a central system (called a container) creates and supplies those objects automatically rather than having the class create them itself. This makes it easier to swap out components during testing or to change how the application is wired together without touching lots of files. The library works primarily through decorators, which are special annotations you attach to a class or its constructor parameters in TypeScript. For example, marking a class with the @injectable decorator tells TSyringe that it can be resolved by the container, meaning the container will create an instance of it and fill in its dependencies. A @singleton decorator does the same thing but ensures only one instance ever exists and is reused each time something asks for it. The container itself is a registry. You can register a class, a factory function, or a plain value under a named token, and then anywhere in your application you resolve that token to get back the object you registered. Child containers are supported for cases where you want a separate scope, and scoped lifetimes are available for finer control over how long instances live. Installing the library requires npm or yarn, and your TypeScript configuration must enable experimental decorators and decorator metadata, which are not on by default. A polyfill for the Reflect API is also required. The README includes working code examples for common scenarios including injection with and without interfaces, singleton registration, and injecting plain values by name. The project is hosted by Microsoft and released under the MIT license.
← microsoft on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.