@ez.dev/di
v2.2.2
Published
A light DI container implementation.
Downloads
462
Maintainers
Readme
@ez.dev/di
A light DI container implementation.
Usage
Basic
You can registry Class, Factory, Value or Alias.
import { Registry } from '@ez.dev/di'
class AuthService {}
const registry = new Registry()
const container = registry
.singleton(AuthService)
.bind('foo', false)
.singleton(Symbol.for('GlobalOptions'), () => ({ bar: true }))
.alias('baz', Symbol.for('GlobalOptions'))
.build()
assert(container.get(AuthService) instanceof AuthService)
assert(container.get('foo') === false)
assert(container.get(Symbol.for('GlobalOptions')).bar === true)
assert(container.get('baz').bar === true)Scopped Container
Create injection sanbox by scopes
const root = new Registry().bind('foo', 1)
const scopped = root.scopped().bind('bar', 2)
const rootContainer = root.build()
const scoppedContainer = scopped.build()
rootContainer.get('foo') // 1
scoppedContainer.get('foo') // 1
rootContainer.get('bar') // throws
rootContainer.tryGet('bar') // null
scoppedContainer.get('bar') // 2Dependencies Injection
Class and Factory providers that requires dependencies will be auto resolved. And typechecking is available during registering.
class Foo {}
class Bar {}
class Baz {
constructor(
private foo: Foo,
private bar: Bar,
) {}
}
const registry = new Registry()
registry
.singleton(Foo)
.singleton(Bar)
.singleton(Baz, [Foo, Bar])
// ^ typechecked, type inferred from constructor parameters
.singleton('GlobalBaz', (foo: Foo, bar: Bar) => new Baz(foo, bar), [Foo, Bar])
// ^ typechecked, type inferred from factory parameters
.build()