Skip to Content
GuidesDependency Item

Dependency Item

A dependency item is the actual implementation that will be injected. There are several types of dependency items.

Class Item

The most common type. The injector will instantiate the class when needed.

// Simple: class is both identifier and item const injector = new Injector([[AuthService]]); // With separate identifier const injector = new Injector([ [IAuthService, { useClass: AuthService }], ]);

Lazy Instantiation

Use lazy: true to defer instantiation until the dependency is actually used:

const injector = new Injector([ [IHttpInterceptor, { useClass: AuthHttpInterceptor, lazy: true }], ]);

Lazy instantiation can improve startup performance by deferring work until it’s needed.

Value Item

Inject a constant value directly:

const injector = new Injector([ [IConfig, { useValue: { apiUrl: 'https://api.example.com', debug: true } }], ]);

Factory Item

Use a function to create the dependency. The factory can have its own dependencies:

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

Existing Item (Alias)

Create an alias for an existing dependency:

const injector = new Injector([ [IHttpInterceptor, { useClass: AuthHttpInterceptor }], [INetworkInterceptor, { useExisting: IHttpInterceptor }], // alias ]); // Both return the same instance injector.get(IHttpInterceptor) === injector.get(INetworkInterceptor); // true

Async Item

Lazy-load a dependency asynchronously (useful for code splitting):

const injector = new Injector([ [ IReportService, { useAsync: () => import('./reportService'), }, ], ]); // In consumer class class OrderService { constructor( @Inject(IReportService) private reportLoader: AsyncHook<IReportService> ) {} async order() { const reportService = await this.reportLoader.whenReady(); reportService.report('Order completed'); } }

Summary

TypeSyntaxUse Case
Class{ useClass: MyClass }Standard service classes
Value{ useValue: obj }Configuration, constants
Factory{ useFactory: fn, deps: [...] }Dynamic creation, conditional logic
Existing{ useExisting: OtherId }Aliases
Async{ useAsync: () => import(...) }Code splitting, lazy loading

onInstantiation Hook

For class and factory items, you can run code right after instantiation:

const injector = new Injector([ [ IConfigService, { useClass: ConfigService, onInstantiation: (service) => service.initialize(), }, ], ]);
Last updated on