fork() function
Home > @rimitive/core > fork
fork() function
Section titled “fork() function”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>>;Parameters
Section titled “Parameters”|
Parameter |
Type |
Description |
|---|---|---|
|
base |
Use<TBase> | |
|
freshModules | ||
|
options |
(Optional) |
Returns:
Use<TBase> | Promise<Use<TBase>>
Example 1
Section titled “Example 1”Basic usage
const root = compose(ConfigModule, DbPoolModule, DbConnectionModule);
// Create a fork with fresh DbConnectionconst 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 instancesscoped.dispose();// root is unaffectedExample 2
Section titled “Example 2”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();});Example 3
Section titled “Example 3”Test isolation
const root = compose(AllModules);
beforeEach(() => { testSvc = fork(root, [StateModule]); // Fresh state per test});
afterEach(() => { testSvc.dispose();});Example 4
Section titled “Example 4”Async fresh modules
const root = await compose(ConfigModule, lazy(DbPoolModule));
// Fork with lazy module returns a Promiseconst scoped = await fork(root, [lazy(DbConnectionModule)]);Example 5
Section titled “Example 5”With instrumentation
const root = compose(ConfigModule, DbPoolModule, { instrumentation });
// Fork can have its own instrumentation for fresh modulesconst scoped = fork(root, [DbConnectionModule], { instrumentation: scopedInstr });