di-scoped
A context-based instantiation system using async_hooks
, ensuring each class instance is scoped to a unique execution context, with automatic creation and reuse of different instances using the same reference across multiple contexts.
This works the same like Scoped ASP.Net Core services, aka These services are created once per HTTP request and are tied to the lifetime of the request (i.e., the HttpContext).
Made for usage with di-kit package
Usage
import { scoped } from 'di-scoped';
export const ScopedService = scoped(class {
constructor(public jwt: string) { }
setJwt = (jwt: string) => {
this.jwt = jwt;
}
getJwt = () => {
return this.jwt;
};
});
export type TScopedService = InstanceType<typeof ScopedService>;
export default ScopedService;
The Context Scoped services for NodeJS
- The constructor arguments are moved to the context creation scope
import { scoped } from 'di-scoped';
const TestClass = scoped(class {
constructor(private name: string) {
}
test() {
console.log(`Hello, ${this.name}`);
}
});
TestClass.runInContext(() => {
new TestClass().test();
}, "Peter")
new TestClass().test();
- The instance reference is similar independent to the context
let instanceRef1;
let instanceRef2;
TestClass.runInContext(() => {
instanceRef1 = new TestClass()
instanceRef1.test()
}, "Peter")
TestClass.runInContext(() => {
instanceRef2 = new TestClass()
instanceRef2.test()
}, "not Peter")
if (TestClass === TestClass) {
console.log("Ok! This is the same class")
}
if (instanceRef1 === instanceRef2) {
console.log("OMG! This is the same instance")
}
See also
If you looking for integrated DI container for scoped services instantiation, take a look on di-kit npm package