Skip to content

Defining the first module

You can define your module by using a builder. It allows to register constant values, class dependencies and externals. Once the module is defined and all externals are resolved, you can build and use it.

Defining constants

To define constants use .register method:

ts
import { 
buildContainer
} from '@hypersphere/dity'
const
module
=
buildContainer
(
c
=>
c
.
register
({
a
: 5,
b
: 'hello world'
})) const
container
=
module
.
build
()
// ℹ️ Container results are properly typed const
a
= await
container
.
get
('a')

Defining class dependencies

To define class dependency, you need to wrap it constructor class with asClass function. You should also decorate it with all dependencies you want to resolve:

Succesful resolution

ts
import { 
buildContainer
,
makeInjector
,
asClass
} from '@hypersphere/dity'
const
module
=
buildContainer
(
c
=>
c
.
register
({
a
: 5,
b
: 'hello world',
dep
:
asClass
(
ClassDep
)
})) const
injector
=
makeInjector
<typeof
module
>()
@
injector
([
'a', 'b' ]) class
ClassDep
{
constructor(
a
: number,
b
: string) { }
} const
container
=
module
.
build
()
// ℹ️ Container results are properly typed const
a
= await
container
.
get
('a')

Type error on type mismatch

ts
import { 
buildContainer
,
makeInjector
,
asClass
} from '@hypersphere/dity'
const
module
=
buildContainer
(
c
=>
c
.
register
({
a
: 5,
b
: 'hello world',
dep
:
asClass
(
ClassDep
)
})) const
injector
=
makeInjector
<typeof
module
>()
@injector([
Unable to resolve signature of class decorator when called as an expression. Argument of type 'typeof ClassDep' is not assignable to parameter of type '(new (args_0: number, args_1: string) => any) | { make(args_0: number, args_1: string): any; } | ((args_0: number, args_1: string) => any)'. Type 'typeof ClassDep' is not assignable to type 'new (args_0: number, args_1: string) => any'. Types of construct signatures are incompatible. Type 'new (a: number, b: number) => ClassDep' is not assignable to type 'new (args_0: number, args_1: string) => any'. Types of parameters 'b' and 'args_1' are incompatible. Type 'string' is not assignable to type 'number'.
'a', 'b' ]) class
ClassDep
{
constructor(
a
: number,
b
: number) { }
} const
container
=
module
.
build
()
// ℹ️ Container results are properly typed const
a
= await
container
.
get
('a')