injec-ts
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

InjectTS

A dependency injection library for TypeScript.

Features

  • Rich, type-safe configuration
  • Infer dependencies from parameter types
  • Use types, strings or symbols to identify dependencies
  • Inject factory functions and optional dependencies
  • Easily control the lifetime of dependencies

Getting Started

  1. Install with NPM
npm install injec-ts
  1. Import and construct a container
import { Container } from 'injec-ts/injec';
let container = new Container();
  1. Resolve your class
let myClass = container.resolve(MyClass);

Configuration

Pass binding configuration into the Container constructor:

import { Container, bind } from 'injec-ts/injec';
let container = new Container([
    bind(Type).toType(SubType),
    bind('string').ToType(Type),
    bind(Symbol('my symbol')).toType(Type),
    bind('something').toValue('some value'),
    bind(AnotherType).to(c => new AnotherType(c.resolve(Dependency)))
]);

Specify dependencies with decorators:

import { Injectable, Named, Optional, Factory, All } from 'injec-ts/injec';
 
@Injectable // Allows inferring dependencies from parameters
class MyClass {
    constructor(
        typedDependency: MyService, // Dependency inferred from parameter type
        @Named('some name') namedDependency: INamedService, // Dependency specified with string or Symbol
        @Optional(OptionalService) optionalDependency?: OptionalService, // Dependency only injected if service is explicitly bound in container
        @Factory(Type, [ParamType]) typeFactory: (param: ParamType) => Type, // Factory method resolves type when called
        @All(BaseService) registeredServices: BaseService[] // Resolves all bindings of specified dependency
    ) { }
}

Package Sidebar

Install

npm i injec-ts

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • soxtoby