Services and injection
A service is a class that holds logic controllers should not: data access, calls to other systems, business rules. Navios wires services with @navios/di, and @navios/server re-exports all of it, so server code imports Injectable, inject and provide from @navios/server.
This page covers what a server developer uses every day. The DI section covers the rest: tokens, providers, scopes, lifecycle and factories.
Declaring and injecting
@Injectable() makes a class resolvable. inject(Class) in a field initialiser asks for an instance.
A controller injects a service the same way:
Three things to know:
- There is no registration step. A service is not listed in a module. Importing the class is enough, and the container creates it the first time something injects it.
inject()works in field initialisers and constructors, while the container is building the instance. It cannot be called later from a method.- Guards, interceptors and modules are services too. They are
@Injectable()classes (a module through@Module) and useinject()exactly like this.
Outside a class, resolve a service from the application with await app.get(UsersService).
Scopes in a server
A scope says how long an instance lives. @Injectable() without options is a singleton.
Because controllers, guards and interceptors are singletons, the same instance serves every request, including concurrent ones. Do not keep per-request data in a field of a singleton.
A singleton cannot inject a request-scoped service: the application fails at init() with a scope mismatch error that names the path, for example UsersController -> UnitOfWork. Most per-request data (the current user, a tenant, a transaction) does not need a request-scoped class at all. Per-request state describes the cheaper tools and when a request-scoped service is the right one.
Providers at a glance
A provider says what a token or a class resolves to. Use one to swap an implementation or to supply a value that is not a class. provide(target, implementation) creates it, and the providers option of a module or of the application registers it.
Anything can then inject(Mailer) and receive a SesMailer, or inject(MailFrom) and receive the string.
Providers are application-wide wherever they are listed; a module does not keep them private. Providers passed to NaviosFactory.create win over those of every module, which is how tests replace dependencies:
The other provider forms (factories, explicit scopes) and the lookup order are in Providers.
Start-up and shutdown work
A service that needs to open a connection or flush a buffer implements onServiceInit() and onServiceDestroy(); see Lifecycle. Hooks tied to the application rather than to one service are on Application setup.