Skip to Content
HeronJS 3.6 with fully support Typescript 6 is released šŸŽ‰
OverviewProvider

Providers are the main building blocks for dependency injection in HeronJS. They hold reusable business logic and can be injected into controllers, services, or other providers.

Provider options

Provider decorators accept configuration such as token and scope.

  • token is the unique identifier used to resolve the provider.
  • scope controls how instances are created and shared.

Create a provider

Use @Provider() for general-purpose injectable classes.

Example file:

  • src/providers/todo.provider.ts
import { Provider, Scope } from '@heronjs/common'; @Provider({ token: 'todo.provider', scope: Scope.SINGLETON, }) export class TodoProvider { async findAll(): Promise<string[]> { return ['todo1', 'todo2']; } }

Use this when the class contains business logic that should be shared across the application.

Create a repository

@Repository() is an alias of @Provider() and is typically used for data access classes.

Example file:

  • src/providers/todo.repository.ts
import { Repository, Scope } from '@heronjs/common'; @Repository({ token: 'todo.repository', scope: Scope.SINGLETON, }) export class TodoRepository { async findAll(): Promise<string[]> { return ['todo1', 'todo2']; } }

Use this naming style when the class is mainly responsible for reading from or writing to a database.

Create a DAO

@Dao() is another alias of @Provider() and is intended for Data Access Object patterns.

Example file:

  • src/providers/todo.dao.ts
import { Dao, Scope } from '@heronjs/common'; @Dao({ token: 'todo.dao', scope: Scope.SINGLETON, }) export class TodoDAO { async findAll(): Promise<string[]> { return ['todo1', 'todo2']; } }

Choose the decorator that best reflects the role of the class in your architecture. All three participate in dependency injection the same way.

Register providers

To make a provider available for injection, register it in the module providers array.

@Module({ providers: [TodoProvider], }) export class AppModule {}

Once registered, HeronJS can resolve the provider anywhere inside that module graph.

Inject a registered provider

Use @Inject() with the provider token to inject it into a controller or another class.

import { Get, Inject, Rest } from '@heronjs/common'; @Rest('/todos') export class TodoController { constructor( @Inject('todo.provider') private readonly provider: TodoProvider, ) {} @Get({ uri: '/' }) public async findAll(): Promise<string[]> { return this.provider.findAll(); } }

In this example, TodoController depends on TodoProvider, and HeronJS resolves that dependency automatically.

Supported scopes

  • Transient
  • Container
  • Singleton
  • Resolution
Last updated on