Quick start
This page takes you from an empty project to two services resolved from a container. DatabaseService and UserService, declared here, are the pair the rest of the DI docs build on.
Install
2.0 is an alpha, published under the next tag. All @navios packages of a project must have the same alpha version, because an alpha may break between releases.
The package has no runtime dependencies. A schema library is only needed for tokens that take arguments.
Check tsconfig
@Injectable and @Factory are standard TC39 decorators, which TypeScript supports from version 5.0 without a flag. The one requirement is that experimentalDecorators is not enabled.
A project that has to keep experimentalDecorators on imports the decorators from a separate entry point. Legacy decorators covers it.
Declare two services
@Injectable() makes a class resolvable. inject() in a field initialiser declares a dependency and returns the instance.
this.db is typed as DatabaseService. Nothing is passed through the constructor, so adding a dependency never changes how a class is created.
Resolve from a container
A container builds instances and keeps them. Create one for the application and ask it for the service you need.
Three things happened:
container.get(UserService)constructedUserService. Itsinject(DatabaseService)call constructedDatabaseServiceon the spot.- Both are singletons by default, so the later
get(DatabaseService)returned the instanceUserServicealready holds. Scopes lists the alternatives. dispose()destroyed both, in reverse order of creation. Lifecycle covers the hooks that run at each end.
Replace a dependency
A container can be told to use a different implementation for a class. This is the basis of testing and of per-environment wiring.
UserService did not change. Providers describes every form provide() accepts, and Testing builds on it.