container-ioc
is an IoC container for Typescript projects. It manages the dependencies between classes, so that applications stay easy to change and maintain as they grow.
Features:
- Angular-like API.
- No dependencies.
- Persistence control.
- Hierarchical containers.
- Pluggable metadata annotator.
Installation:
npm install --save container-ioc
Quick start
import { Container, Inject, Injectable } from 'container-ioc';
let container = new Container();
@Injectable()
class App {}
interface IService {}
@Injectable()
class Service implements IService {
constructor(@Inject('ISerivce') public service: IService) {}
}
let providers = [
{ token: App, useClass: App },
{ token: 'IService', useClass: Service }
];
container.register(providers);
let app = container.resolve(App);
Examples:
Persistence control.
By default, resolved instances are singletons. You can change that by setting provider's attribute LifeTime to LifeTime.PerRequest.
import { Container, Injectable, LifeTime } from 'container-ioc';
const container = new Container();
@Injectable()
class A {}
container.register({ token: A, useClass: A, lifeTime: LifeTime.PerRequest });
const instance1 = container.resolve(A);
const instance2 = container.resolve(A);
// instance1 !== instance2
Injection Token
InjectionToken helps to avoid hardcoded strings in your code.
Without InjectionToken:
interface IService {}
@Injectable()
class ConcreteService {}
container.register({ token: 'IService', useClass: ConcreteService });
container.resolve('IService');
With InjectionToken
interface IService {}
const TService = new InjectionToken<IService>('IService'); // T stands for Token, you can pick another prefix
@Injectable()
class ConcreteService {}
container.register({ token: TService, useClass: ConcreteService });
container.resolve(TService);
Hierarchical containers.
if a provider wasn't found in a container it will look up in ascendant containers if there are any:
import { Container } from 'container-ioc';
@Injectable()
class A {}
let parentContainer = new Container();
let childContainer = parentContainer.createScope();
parentContainer.register({ token: 'IA', useClass: A });
childContainer.resolve('IA');
Pluggable metadata annotator.
By default metadata is assigned to static properties. If you want to use Reflect API for annotation, you can implement IMetadataAnnotator interface with your implementation using Reflect API. Then plug it into AnnotatorProvider
import { AnnotatorProvider, IMetadataAnnotator, Container } from 'container-ioc';
class ReflectMetadataAnnotator implements IMetadataAnnotator {
// your implementation
}
AnnotatorProvider.set(new ReflectMetadataAnnotator());
let container = new Container();
...
Contribution:
Feel free to submit a bug or a feature request. Or pick an issue from here and leave a comment with your proposal.
see CONTRIBUTION.md