symboldi
v3.0.1
Published
Dependency injection with service lifetime without dependencies for TypeScript.
Downloads
48
Maintainers
Readme
SymbolDI
SymbolDI is a tool to use dependency injection with service lifetime. It is dependency free and in particular doesn't need reflect-metadata to work. Instead it creates typed symbols which can be used to retrieve the data. As such it isn't limited to classes but can also be used with primitives, arrays and plain objects.
Inspired by Dependency injection in .NET and the new-found possibilities of AsyncLocalStorage.
Installation
npm install symboldi
If you want to use decorators make sure you have TypeScript 5 or higher installed and experimentalDecorators disabled, which is the default.
Basic Usage
- create a container
- create some refs
- register some services by ref and factory
- get typed object by container with ref
service.ts
import { Container } from 'symboldi';
// empty container
export const container = Container.factory()
// define ref for session
export const sessionRef = Container.ref<string>()
register.ts
import { sessionRef, container } from './service.js'
import crypto from 'crypto'
container.addScoped(() => crypto.randomUUID(), sessionRef)
use.ts
import { sessionRef, container } from './service.js'
import './register.js'
// get current session
const currentSession = container.get(sessionRef)
// renew scope
container.scopeRenew()
// get next session
const nextSession = container.get(sessionRef)
// ceff046e-ceb0-456e-875b-3010792e1294 dbe8fd2e-99c4-4f03-b57e-b930a90249f2
console.log(currentSession, nextSession)
Documentation
The documentation is build with TypeDoc and hosted on GitHub Pages at https://ml1nk.github.io/symboldi.