Simple and lightweight injector for typescript projects.
npm install @xeinebiu/ts_injector@1.0.2
Module allows you to provide
classes when they are requested via injection
createDiModule({
provides: [{
provide: FeedRepository
}]
})
On the example above, we are providing FeedRepository
on any scope
required.
Now, to use it, simply annotate the property with @Inject()
class Demo {
@Inject()
private readonly feedRepository!: FeedRepository
}
To make the FeedRepository
a singleton, simply add singleton: true
FeedReposiotory
class must not be abstract
createDiModule({
provides: [{
provide: FeedRepository,
singleton: true
}]
})
Whether your project is built in on abstraction, the following example can be used.
createDiModule({
provides: [{
singleton: true,
provide: FeedRepository, // can also be abstract when used with `useClass`
useClass: DemoFeedRepository
}]
})
DemoFeedRepository
will be provided for FeedRepository
. Since we are setting singleton: true
, a single instance is shared.
Provide a class instance for requested provider.
createDiModule({
provides: [{
provide: FeedRepository, // can also be abstract when used with `useValue`
useValue: new DemoFeedRepository(...arguments)
}]
})
When useValue
is used, singleton is set by default to true
Using scope
allows providing different classes on specific scope.
createDiModule({
provides: [{
provide: FeedRepository,
useClass: RootFeedRepository,
provideIn: 'root'
}]
})
It is a must to annotate the class where the scope is needed.
@Scope({
scope: 'root'
})
class RootDemo {
@Inject()
private readonly feedRepository!: FeedRepository
}
feedRepository
on RootDemo
is provided with RootFeedRepository