Skip to content

fork() function

Home > @rimitive/core > fork

Create a new composition that shares instances from an existing one, but with fresh instances of specified modules.

Fresh modules are: - Re-instantiated (not shared with the base) - Singleton within the fork (shared by dependents in the forked context) - Disposed when the fork is disposed (base instances are not affected)

Fresh modules can depend on base instances - they receive the base singletons as their dependencies.

Signature:

export declare function fork<TBase>(base: Use<TBase>, freshModules: AnyModule[], options?: ForkOptions): Use<TBase> | Promise<Use<TBase>>;

Parameter

Type

Description

base

Use<TBase>

freshModules

AnyModule[]

options

ForkOptions

(Optional)

Returns:

Use<TBase> | Promise<Use<TBase>>

Basic usage

const root = compose(ConfigModule, DbPoolModule, DbConnectionModule);
// Create a fork with fresh DbConnection
const scoped = fork(root, [DbConnectionModule]);
scoped.config // Same instance as root (shared)
scoped.dbPool // Same instance as root (shared)
scoped.dbConnection // Fresh instance (not root's)
// Cleanup fresh instances
scoped.dispose();
// root is unaffected

Per-request context in a server

const root = compose(ConfigModule, DbPoolModule);
app.use((req, res, next) => {
req.svc = fork(root, [DbConnectionModule, RequestContextModule]);
res.on('finish', () => req.svc.dispose());
next();
});

Test isolation

const root = compose(AllModules);
beforeEach(() => {
testSvc = fork(root, [StateModule]); // Fresh state per test
});
afterEach(() => {
testSvc.dispose();
});

Async fresh modules

const root = await compose(ConfigModule, lazy(DbPoolModule));
// Fork with lazy module returns a Promise
const scoped = await fork(root, [lazy(DbConnectionModule)]);

With instrumentation

const root = compose(ConfigModule, DbPoolModule, { instrumentation });
// Fork can have its own instrumentation for fresh modules
const scoped = fork(root, [DbConnectionModule], { instrumentation: scopedInstr });