1.0 Dependency injection
Injector: The injector object that exposes APIs to us to create instances of dependencies.
Provider: A provider is like a recipe that tells the injector how to create an instance of a dependency. A provider is a Function token or a IProvider object.
Dependency: A dependency is the type of which an object should be created.
export interface IProvider {
provide: any;
useValue?: any;
useClass?: Function;
useFactory?: Function;
deps?: Array<Function|IProvider>;
}
@Injectable() - is an empty @Provider
@Provider([ServiceA, ServiceB]) - provide list of dependencies required by class.
@Inject(Token) - is used to inject
// Constructor
@Injectable()
export class Car {
constructor(
@Inject(Engine) engine,
@Inject(Tires) tires
) {
// access to tiers and engine
}
}
// Constructor without @Inject
@Injectable()
export class Car {
constructor(
engine: Engine,
tires: Tires
) {}
}
// Injection point via @Inject after object is initialized
@Injectable()
export class Car implements IAfterConstruct {
@Inject(Engine) engine: Engine;
@Inject(Tires) tires: Tires;
afterConstruct() {
// access to this.engine, this.tires
}
getEngine() {
return this.engine;
}
}
How to create an instance of Car via Injector:
import { Injector } from “typeix”;
var injector = Injector.createAndResolve(Car, [
Engine,
Tires
]);
var car: Car = injector.get(Car);
Type of injection providers:
Token:
var injector = Injector.createAndResolve(Car, [
Engine
]);
Is equal to:
var injector = Injector.createAndResolve(Car, [
{
provide: Engine,
useClass: Engine
}
]);
This is useful for providing custom implementations or mocks for testing purposes.
Providing custom value:
var injector = Injector.createAndResolve(Car, [
{
provide: Engine,
useValue: new Engine()
}
]);
Providing factory:
var injector = Injector.createAndResolve(Car, [
{
provide: Engine,
useFactory: (a, b) => new Engine(a, b),
deps: [ServiceA, ServiceB]
}
]);
More about dependency injection.