Documentation chapters
You're looking at legacy documentation.
New multi-language documentation available at https://docs.deepkit.io
Framework

Services

Service is a broad category encompassing any value, function, or feature that an application needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.

A service in Deepkit (and in most other JavaScript/TypeScript frameworks) is a simple class registered in a module using a provider. The simplest provider is the class provider, which specifies only the class itself and nothing else. It then becomes a singleton in the dependency injection container of the module where it was defined.

Services are handled and instantiated by the dependency injection container and thus can be imported and used in other services, in controllers, and event listeners using constructor injection or property injection. See the chapter Dependency injection for more details.

To create a simple service, you write a class with a purpose:

export interface User {
    username: string;
}

export class UserManager {
    users: User[] = [];

    addUser(user: User) {
        this.users.push(user);
    }
}

And either register it in your application, or in a module:

new App({
    providers: [UserManager]
}).run();

After doing so you can use this service in controllers, other services, or event listeners. For example, let's reuse our CLI TestCommand from the Getting Started chapter.

import { UserManger } from './services/user-manager';

@cli.controller('test')
export class TestCommand implements Command {
    constructor(protected userManager: UserManager) {
    }

    async execute() {
        this.userManager.addUser({username: 'Peter'});
    }
}

There are several ways to define how the services is instantiated. See the chapter Dependency injection for more details.

Made in Germany