@xeinebiu/ts_injector
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

Typescript Injector

Simple and lightweight injector for typescript projects.


Installation

npm install @xeinebiu/ts_injector@1.0.0

Modules

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
}

Providers

Singleton

To make the FeedRepository a singleton, simply add singleton: true

FeedReposiotory class must not be abstract

createDiModule({
    provides: [{
        provide: FeedRepository,
        singleton: true
    }]
})

Use Class

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.

Use Value

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


Scope

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

Package Sidebar

Install

npm i @xeinebiu/ts_injector

Weekly Downloads

0

Version

1.0.2

License

ISC

Unpacked Size

38.6 kB

Total Files

71

Last publish

Collaborators

  • xeinebiu