Gathering detailed insights and metrics for tsyringe
Gathering detailed insights and metrics for tsyringe
Gathering detailed insights and metrics for tsyringe
Gathering detailed insights and metrics for tsyringe
@discordx/di
dependency injection service with TSyringe support
@kalendell/tsyringe
[![Travis](https://img.shields.io/travis/Microsoft/tsyringe.svg)](https://travis-ci.org/Microsoft/tsyringe/) [![npm](https://img.shields.io/npm/v/tsyringe.svg)](https://www.npmjs.com/package/tsyringe) [![npm](https://img.shields.io/npm/dt/tsyringe.svg)]
@hono/tsyringe
The tsyringe dependency injection middleware for Hono
esbuild-shake-tsyringe-tree
This plugin is designed to shake tree (remove code unused) mainly with the lib tsyringe. Attention: Currently only works with ES Module (.mjs)
Lightweight dependency injection container for JavaScript/TypeScript
npm install tsyringe
99.6
Supply Chain
100
Quality
78.4
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,187 Stars
169 Commits
172 Forks
42 Watching
6 Branches
10,000 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (99.43%)
JavaScript (0.57%)
Cumulative downloads
Total Downloads
Last day
-1.5%
77,588
Compared to previous day
Last week
11.1%
430,911
Compared to previous week
Last month
16.5%
1,688,050
Compared to previous month
Last year
46.4%
16,246,909
Compared to previous year
A lightweight dependency injection container for TypeScript/JavaScript for constructor injection.
Install by npm
1npm install --save tsyringe
or install with yarn
(this project is developed using yarn
)
1yarn add tsyringe
Modify your tsconfig.json
to include the following settings
1{ 2 "compilerOptions": { 3 "experimentalDecorators": true, 4 "emitDecoratorMetadata": true 5 } 6}
Add a polyfill for the Reflect API (examples below use reflect-metadata). You can use:
The Reflect polyfill import should only be added once, and before DI is used:
1// main.ts 2import "reflect-metadata"; 3 4// Your code here...
If you're using Babel (e.g. using React Native), you will need to configure it to emit TypeScript metadata.
First get the Babel plugin
yarn add --dev babel-plugin-transform-typescript-metadata
npm install --save-dev babel-plugin-transform-typescript-metadata
Then add it to your Babel config
plugins: [
'babel-plugin-transform-typescript-metadata',
/* ...the rest of your config... */
]
TSyringe performs Constructor Injection on the constructors of decorated classes.
Class decorator factory that allows the class' dependencies to be injected at runtime. TSyringe relies on several decorators in order to collect metadata about classes to be instantiated.
1import {injectable} from "tsyringe"; 2 3@injectable() 4class Foo { 5 constructor(private database: Database) {} 6} 7 8// some other file 9import "reflect-metadata"; 10import {container} from "tsyringe"; 11import {Foo} from "./foo"; 12 13const instance = container.resolve(Foo);
Class decorator factory that registers the class as a singleton within the global container.
1import {singleton} from "tsyringe"; 2 3@singleton() 4class Foo { 5 constructor() {} 6} 7 8// some other file 9import "reflect-metadata"; 10import {container} from "tsyringe"; 11import {Foo} from "./foo"; 12 13const instance = container.resolve(Foo);
Class decorator factory that replaces the decorated class' constructor with a parameterless constructor that has dependencies auto-resolved.
Note Resolution is performed using the global container.
1import {autoInjectable} from "tsyringe"; 2 3@autoInjectable() 4class Foo { 5 constructor(private database?: Database) {} 6} 7 8// some other file 9import {Foo} from "./foo"; 10 11const instance = new Foo();
Notice how in order to allow the use of the empty constructor new Foo()
, we
need to make the parameters optional, e.g. database?: Database
.
Parameter decorator factory that allows for interface and other non-class information to be stored in the constructor's metadata.
1import {injectable, inject} from "tsyringe"; 2 3interface Database { 4 // ... 5} 6 7@injectable() 8class Foo { 9 constructor(@inject("Database") private database?: Database) {} 10}
Parameter decorator for array parameters where the array contents will come from the container. It will inject an array using the specified injection token to resolve the values.
1import {injectable, injectAll} from "tsyringe"; 2 3@injectable() 4class Foo {} 5 6@injectable() 7class Bar { 8 constructor(@injectAll(Foo) fooArray: Foo[]) { 9 // ... 10 } 11}
Parameter decorator which allows for a transformer object to take an action on the resolved object before returning the result.
1class FeatureFlags { 2 public getFlagValue(flagName: string): boolean { 3 // ... 4} 5 6class Foo() {} 7 8class FeatureFlagsTransformer implements Transform<FeatureFlags, bool> { 9 public transform(flags: FeatureFlags, flag: string) { 10 return flags.getFlagValue(flag); 11 } 12} 13 14@injectable() 15class MyComponent(foo: Foo, @injectWithTransform(FeatureFlags, FeatureFlagsTransformer, "IsBlahEnabled") blahEnabled: boolean){ 16 // ... 17}
This parameter decorator allows for array contents to be passed through a transformer. The transformer can return any type, so this can be used to map or fold an array.
1@injectable() 2class Foo { 3 public value; 4} 5 6class FooTransform implements Transform<Foo[], string[]>{ 7 public transform(foos: Foo[]): string[]{ 8 return foos.map(f => f.value)); 9 } 10} 11 12@injectable() 13class Bar { 14 constructor(@injectAllWithTransform(Foo, FooTransform) stringArray: string[]) { 15 // ... 16 } 17}
Class decorator factory that registers the class as a scoped dependency within the global container.
1@scoped(Lifecycle.ContainerScoped) 2class Foo {}
The general principle behind Inversion of Control (IoC) containers
is you give the container a token, and in exchange you get an instance/value. Our container automatically figures out the tokens most of the time, with 2 major exceptions, interfaces and non-class types, which require the @inject()
decorator to be used on the constructor parameter to be injected (see above).
In order for your decorated classes to be used, they need to be registered with the container. Registrations take the form of a Token/Provider pair, so we need to take a brief diversion to discuss tokens and providers.
A token may be either a string, a symbol, a class constructor, or a instance of DelayedConstructor
.
1type InjectionToken<T = any> = 2 | constructor<T> 3 | DelayedConstructor<T> 4 | string 5 | symbol;
Our container has the notion of a provider. A provider is registered with the DI container and provides the container the information needed to resolve an instance for a given token. In our implementation, we have the following 4 provider types:
1{ 2 token: InjectionToken<T>; 3 useClass: constructor<T>; 4}
This provider is used to resolve classes by their constructor. When registering a class provider you can simply use the constructor itself, unless of course you're making an alias (a class provider where the token isn't the class itself).
1{ 2 token: InjectionToken<T>; 3 useValue: T 4}
This provider is used to resolve a token to a given value. This is useful for registering constants, or things that have a already been instantiated in a particular way.
1{ 2 token: InjectionToken<T>; 3 useFactory: FactoryFunction<T>; 4}
This provider is used to resolve a token using a given factory. The factory has full access to the dependency container.
We have provided 2 factories for you to use, though any function that matches the FactoryFunction<T>
signature
can be used as a factory:
1type FactoryFunction<T> = (dependencyContainer: DependencyContainer) => T;
This factory is used to lazy construct an object and cache result, returning the single instance for each subsequent
resolution. This is very similar to @singleton()
1import {instanceCachingFactory} from "tsyringe"; 2 3{ 4 token: "SingletonFoo"; 5 useFactory: instanceCachingFactory<Foo>(c => c.resolve(Foo)); 6}
This factory is used to lazy construct an object and cache result per DependencyContainer
, returning the single instance for each subsequent
resolution from a single container. This is very similar to @scoped(Lifecycle.ContainerScoped)
1import {instancePerContainerCachingFactory} from "tsyringe"; 2 3{ 4 token: "ContainerScopedFoo"; 5 useFactory: instancePerContainerCachingFactory<Foo>(c => c.resolve(Foo)); 6}
This factory is used to provide conditional behavior upon resolution. It caches the result by default, but has an optional parameter to resolve fresh each time.
1import {predicateAwareClassFactory} from "tsyringe"; 2 3{ 4 token: "FooHttp", 5 useFactory: predicateAwareClassFactory<Foo>( 6 c => c.resolve(Bar).useHttps, // Predicate for evaluation 7 FooHttps, // A FooHttps will be resolved from the container if predicate is true 8 FooHttp // A FooHttp will be resolved if predicate is false 9 ); 10}
1{ 2 token: InjectionToken<T>; 3 useToken: InjectionToken<T>; 4}
This provider can be thought of as a redirect or an alias, it simply states that given token x, resolve using token y.
The normal way to achieve this is to add DependencyContainer.register()
statements somewhere
in your program some time before your first decorated class is instantiated.
1container.register<Foo>(Foo, {useClass: Foo}); 2container.register<Bar>(Bar, {useValue: new Bar()}); 3container.register<Baz>("MyBaz", {useValue: new Baz()});
As an optional parameter to .register()
you may provide RegistrationOptions
which customize how the registration behaves. See the linked source code for up to date documentation
on available options.
You can also mark up any class with the @registry()
decorator to have the given providers registered
upon importing the marked up class. @registry()
takes an array of providers like so:
1@registry([ 2 { token: Foobar, useClass: Foobar }, 3 { token: "theirClass", useFactory: (c) => { 4 return new TheirClass( "arg" ) 5 }, 6 } 7]) 8class MyClass {}
This is useful when you want to register multiple classes for the same token.
You can also use it to register and declare objects that wouldn't be imported by anything else,
such as more classes annotated with @registry
or that are otherwise responsible for registering objects.
Lastly you might choose to use this to register 3rd party instances instead of the container.register(...)
method.
note: if you want this class to be @injectable
you must put the decorator before @registry
, this annotation is not
required though.
Resolution is the process of exchanging a token for an instance. Our container will recursively fulfill the dependencies of the token being resolved in order to return a fully constructed object.
The typical way that an object is resolved is from the container using resolve()
.
1const myFoo = container.resolve(Foo); 2const myBar = container.resolve<Bar>("Bar");
You can also resolve all instances registered against a given token with resolveAll()
.
1interface Bar {} 2 3@injectable() 4class Foo implements Bar {} 5@injectable() 6class Baz implements Bar {} 7 8@registry([ 9 // registry is optional, all you need is to use the same token when registering 10 {token: "Bar", useToken: Foo}, // can be any provider 11 {token: "Bar", useToken: Baz} 12]) 13class MyRegistry {} 14 15const myBars = container.resolveAll<Bar>("Bar"); // myBars type is Bar[]
Interception allows you to register a callback that will be called before or after the resolution of a specific token. This callback can be registered to execute only once (to perform initialization, for example), on each resolution to do logging, for example.
beforeResolution
is used to take an action before an object is resolved.
1class Bar {} 2 3container.beforeResolution( 4 Bar, 5 // Callback signature is (token: InjectionToken<T>, resolutionType: ResolutionType) => void 6 () => { 7 console.log("Bar is about to be resolved!"); 8 }, 9 {frequency: "Always"} 10);
afterResolution
is used to take an action after the object has been resolved.
1class Bar { 2 public init(): void { 3 // ... 4 } 5} 6 7container.afterResolution( 8 Bar, 9 // Callback signature is (token: InjectionToken<T>, result: T | T[], resolutionType: ResolutionType) 10 (_t, result) => { 11 result.init(); 12 }, 13 {frequency: "Once"} 14);
If you need to have multiple containers that have disparate sets of registrations, you can create child containers:
1const childContainer1 = container.createChildContainer(); 2const childContainer2 = container.createChildContainer(); 3const grandChildContainer = childContainer1.createChildContainer();
Each of the child containers will have independent registrations, but if a registration is absent in the child container at resolution, the token will be resolved from the parent. This allows for a set of common services to be registered at the root, with specialized services registered on the child. This can be useful, for example, if you wish to create per-request containers that use common stateless services from the root container.
The container.clearInstances()
method allows you to clear all previously created and registered instances:
1class Foo {} 2@singleton() 3class Bar {} 4 5const myFoo = new Foo(); 6container.registerInstance("Test", myFoo); 7const myBar = container.resolve(Bar); 8 9container.clearInstances(); 10 11container.resolve("Test"); // throws error 12const myBar2 = container.resolve(Bar); // myBar !== myBar2 13const myBar3 = container.resolve(Bar); // myBar2 === myBar3
Unlike with container.reset()
, the registrations themselves are not cleared.
This is especially useful for testing:
1@singleton() 2class Foo {} 3 4beforeEach(() => { 5 container.clearInstances(); 6}); 7 8test("something", () => { 9 container.resolve(Foo); // will be a new singleton instance in every test 10});
Sometimes you need to inject services that have cyclic dependencies between them. As an example:
1@injectable() 2export class Foo { 3 constructor(public bar: Bar) {} 4} 5 6@injectable() 7export class Bar { 8 constructor(public foo: Foo) {} 9}
Trying to resolve one of the services will end in an error because always one of the constructor will not be fully defined to construct the other one.
1container.resolve(Foo);
Error: Cannot inject the dependency at position #0 of "Foo" constructor. Reason:
Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.
delay
helper functionThe best way to deal with this situation is to do some kind of refactor to avoid the cyclic dependencies. Usually this implies introducing additional services to cut the cycles.
But when refactor is not an option you can use the delay
function helper. The delay
function wraps the constructor in an instance of DelayedConstructor
.
The delayed constructor is a kind of special InjectionToken
that will eventually be evaluated to construct an intermediate proxy object wrapping a factory for the real object.
When the proxy object is used for the first time it will construct a real object using this factory and any usage will be forwarded to the real object.
1@injectable() 2export class Foo { 3 constructor(@inject(delay(() => Bar)) public bar: Bar) {} 4} 5 6@injectable() 7export class Bar { 8 constructor(@inject(delay(() => Foo)) public foo: Foo) {} 9} 10 11// construction of foo is possible 12const foo = container.resolve(Foo); 13 14// property bar will hold a proxy that looks and acts as a real Bar instance. 15foo.bar instanceof Bar; // true
We can rest in the fact that a DelayedConstructor
could be used in the same contexts that a constructor and will be handled transparently by tsyringe. Such idea is used in the next example involving interfaces:
1export interface IFoo {} 2 3@injectable() 4@registry([ 5 { 6 token: "IBar", 7 // `DelayedConstructor` of Bar will be the token 8 useToken: delay(() => Bar) 9 } 10]) 11export class Foo implements IFoo { 12 constructor(@inject("IBar") public bar: IBar) {} 13} 14export interface IBar {} 15 16@injectable() 17@registry([ 18 { 19 token: "IFoo", 20 useToken: delay(() => Foo) 21 } 22]) 23export class Bar implements IBar { 24 constructor(@inject("IFoo") public foo: IFoo) {} 25}
All instances created by the container that implement the Disposable
interface will automatically be disposed of when the container is disposed.
1container.dispose();
or to await all asynchronous disposals:
1await container.dispose();
Since classes have type information at runtime, we can resolve them without any extra information.
1// Foo.ts 2export class Foo {}
1// Bar.ts 2import {Foo} from "./Foo"; 3import {injectable} from "tsyringe"; 4 5@injectable() 6export class Bar { 7 constructor(public myFoo: Foo) {} 8}
1// main.ts 2import "reflect-metadata"; 3import {container} from "tsyringe"; 4import {Bar} from "./Bar"; 5 6const myBar = container.resolve(Bar); 7// myBar.myFoo => An instance of Foo
Interfaces don't have type information at runtime, so we need to decorate them
with @inject(...)
so the container knows how to resolve them.
1// SuperService.ts 2export interface SuperService { 3 // ... 4}
1// TestService.ts 2import {SuperService} from "./SuperService"; 3export class TestService implements SuperService { 4 //... 5}
1// Client.ts 2import {injectable, inject} from "tsyringe"; 3 4@injectable() 5export class Client { 6 constructor(@inject("SuperService") private service: SuperService) {} 7}
1// main.ts 2import "reflect-metadata"; 3import {Client} from "./Client"; 4import {TestService} from "./TestService"; 5import {container} from "tsyringe"; 6 7container.register("SuperService", { 8 useClass: TestService 9}); 10 11const client = container.resolve(Client); 12// client's dependencies will have been resolved
Primitive values can also be injected by utilizing named injection
1import {singleton, inject} from "tsyringe"; 2 3@singleton() 4class Foo { 5 private str: string; 6 constructor(@inject("SpecialString") value: string) { 7 this.str = value; 8 } 9} 10 11// some other file 12import "reflect-metadata"; 13import {container} from "tsyringe"; 14import {Foo} from "./foo"; 15 16const str = "test"; 17container.register("SpecialString", {useValue: str}); 18 19const instance = container.resolve(Foo);
The following is a list of features we explicitly plan on not adding:
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
No vulnerabilities found.
Reason
security policy file detected
Details
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 8/14 approved changesets -- score normalized to 5
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
20 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More