Dependency injection

This section covers the use of dependency injection in Nokron. Dependency injection (DI) is a technique for achieving Inversion of Control (IoC) between classes and their dependencies (services). It is a form of the Service Locator pattern. In Nokron, DI is implemented using the TSyringe library.


Services

Services are classes that are used to provide functionality to other classes. They are usually used to provide access to external resources, such as databases, APIs, etc. Services are registered in the services directory of the project. The services directory is located in the src directory of the project.

For dependency injection to work, all services must be registered as a part of the module. The module will ensure that the service is registered and available to all classes that depend on it, such as controllers and other services.

Creating a service

Creating a services is as simple as creating a class. The only requirement is that the service class must be decorated with the @Service() decorator.

import { Service } from '@nokron/core';
 
@Service()
export class MyService {
  public doSomething(): void {
    // Do something
  }
}

Registering a service

To register a service, it must be added to the providers array of the module. The providers array is located in the @Module() decorator of the module.

const MainModule = new Module({
  name: 'Main',
  providers: [
    MyService,
  ],
});

Injecting a service

Now that the service is registered to the module, it can be used in controllers and other services by injecting it into the constructor of the class.

import { Controller, HttpGet, Ok } from '@nokron/core';
 
@Controller("/my-controller")
export class MyController {
  constructor(
    private myService: MyService,
  ) {}
 
  @HttpGet('/do-something')
  public doSomething() {
    this.myService.doSomething();
 
    return Ok();
  }
}

Accessing the container

Additionally, the service collection can be accessed directly in order to retrieve services. This is useful when a service is not available to be injected into a class or when a service is not registered to a module.

The service collection is accessible through the ServiceProvider class. The ServiceProvider class is a singleton that is available to all classes in the application and provides a series of tools for working with services.

import { ServiceProvider } from '@nokron/core';
 
class MyClass {
  constructor(
    private serviceProvider: ServiceProvider,
  ) {}
 
  public doSomething() {
    const myService = this.serviceProvider.getService(MyService);
 
    myService.doSomething();
  }
}