Migrating to 2.0
Version 2.0 replaces the resolution engine of @navios/di. Resolution is synchronous first, a token is identified by the object, the global registry and priorities give way to explicit providers, and a service is always built in the scope it declares. This page lists every public change from 1.x and shows the ones most applications meet.
Server applications should read Migrating to 2.0 for the framework changes; this page covers only the container.
What changed
New in 2.0: provide() with { existing } aliases, registerProvider(), inject(ScopedContainer), container.provide() and container.decorate() (both throw once the token is resolved), container.getSync(), container.instances(), container.onInvalidate(), container.getProvider(), registerInjectable(), registerFactory(), ContainerOptions.strict, tokens that declare a scope, Symbol.asyncDispose on containers and scopes, and the error codes ProviderConflict, AsyncInitRequired, ContainerDisposed, OutsideInjectionContext and AccessBeforeInit.
Unchanged: @Injectable({ scope, token, schema }), @Factory({ scope, token }), inject, asyncInject, optional, InjectionToken.bound, InjectionToken.factory, InjectionToken.refineType, the lifecycle hooks, container.get, invalidate, dispose, ready, addInstance, isRegistered, InjectableScope, getInjectableToken, the create(ctx, args) signature of factories, and the @navios/di/legacy-compat entry point.
Registries and priorities become providers
A token accepts one default. Remove token from every alternative and bind the one you want with provide().
A custom registry that existed only to isolate tests needs no replacement: each Container has its own instances. Code that re-registered a service with a higher priority in order to wrap it should use container.decorate().
Request contexts become scopes
A try/finally with scope.dispose() works too. Scopes have no id; if you need one, add it to the scope as a value.
Scope mismatches are errors
In 1.x this singleton was turned into a request-scoped service without notice:
In 2.0 resolving AuditService fails with ScopeMismatchError. To keep the old behaviour, declare it: @Injectable({ scope: InjectableScope.Request }) on AuditService. Scopes lists the other options.
inject works for transients
Existing asyncInject() calls keep working. They are only needed to break a cycle.
Tokens have no ids
Code that looked services up by token.id or by a name string has to hold on to the token object. Two tokens created with the same name are different tokens. Existing Zod schemas work unchanged, except those that validate asynchronously.
Instance names and the event bus are gone
The storage, registry, resolver and tracker accessors have no public replacement.
Behaviour to check
- Errors are wrapped. A test that compared a rejection with the original error by identity must read
error.cause. The message still contains the original message, sorejects.toThrow('boom')keeps passing. optional()no longer hides failures. If code relied on it to tolerate a service that fails to construct, handle the failure inside the service or resolve it withcontainer.get()in atryblock.- Constructors run once. Guards against double construction can be removed. Constructors should still be free of side effects and should not use injected services; see constructor replay.
- Singletons are built against the root container. A value added with
scope.addInstance()is not visible to a singleton, even when the singleton is first requested through that scope. - Factory token values are per container. They used to be cached on the token and shared by all containers.
- A disposed container is closed. Code that used one again has to create a new
Container. - Implementations are type-checked.
provide(),addInstance()and the testing containers reject what lacks public members of the target. A partial mock needs a cast. - A value for a request-scoped token belongs to a scope.
addInstance()on the root container fails withScopeMismatchErrorfor it. create()makes a factory only with aFactoryContextfirst, or without parameters. That is how types are inferred; a service whosecreate()takes its own data is no longer typed as a factory.- Errors carry no arguments.
contextof aTokenValidationErroris{ name, issues: { path, message }[] }, without the schema and the value. - Destroy errors are printed. Without a
logger, whatonServiceDestroy()throws goes toconsole.error(). - Root-level transients are not tracked. A transient resolved directly from the root container no longer has
onServiceDestroycalled bydispose(). - Arguments that are
undefinedcount as absent.{ id, opt: undefined }and{ id }are one instance, and dates, maps, sets and URLs are compared by value. - Falsy values are injected as they are. A token bound to
0,'',falseornullresolves to that value. - Classes with identical source are distinct. Token ids derived from class source are gone, so two classes produced by the same function no longer share an instance.
Tests
- Replace
new Container(new Registry())withnew Container(). - Replace priority-based overrides with
new Container({ providers: [provide(Token, Mock)] })orTestContainer#bind(). - A value bound for a request-scoped token is served by scopes only.
TestContainerhas noparentRegistryoption.clear()keeps what was bound, and the factory given totoFactory()receives the factory context and the arguments.UnitTestContaineris a strict container: only itsprovidersresolve.getRegisteredTokenIds()andgetAutoMockedTokenIds()aregetRegisteredTokens()andgetAutoMockedTokens(), which hold the tokens.useFactoryreceives the context and the arguments.clear()leaves both usable;dispose()closes them.- Delete tests that asserted removed behaviour: priorities, scope upgrade, request ids, token ids, "Wrong token order", double construction.