Skip to Content
GuidesDeclare Dependency

Declare Dependency

Once you have identifiers and dependency items, you need to declare the relationships between them.

On a Class

Use the @Inject decorator on constructor parameters:

class MapService { constructor( @Inject(SatelliteService) private readonly satellite: SatelliteService ) {} }

You can also use an IdentifierDecorator directly:

interface IPlatformService {} const IPlatformService = createIdentifier<IPlatformService>("platform"); class DialogService { constructor( @IPlatformService private readonly platform: IPlatformService ) {} }

On a Factory

List dependencies in the deps array:

const injector = new Injector([ [I18NService], [ IFormatter, { useFactory: (i18n: I18NService) => { return i18n.isChinese() ? new ChineseFormatter() : new EnglishFormatter(); }, deps: [I18NService], }, ], ]);

Optional Dependencies

By default, missing dependencies throw an error. Use @Optional to allow null:

class MapService { constructor( @Optional(SatelliteService) private readonly satellite?: SatelliteService ) {} } const injector = new Injector([[MapService]]); injector.get(MapService); // Works! satellite is undefined

Multiple Instances

Use @Many to inject all registered instances as an array:

class MapService { constructor( @Many(ISatelliteService) private readonly satellites: ISatelliteService[] ) {} } const injector = new Injector([ [MapService], [ISatelliteService, { useClass: GPSSatellite }], [ISatelliteService, { useClass: BeidouSatellite }], ]); // satellites array contains both GPS and Beidou instances
Last updated on