Dependency injection for TypeScript : https://mickgrz.github.io/injects/
Use a class instance without instantiate it.
The responsibility of providing dependency is delegated to an injector.
This separates the responsibilities of usages and construction.
This also improves readability, testability & maintainability.
class Dao {
public create(entity: any) {
[...]
}
}
import {inject} from 'injects';
import Dao from './Dao';
class Service {
private dao: Dao;
constructor() {
this.dao = inject(Dao);
}
public create(entity: any) {
return this.dao.create(entity);
}
}
const service: Service = new Service();
service.create({ entityId: 1 });// will call dao.create
You can also write :
import {inject} from 'injects';
import Dao from './Dao';
class Service {
private dao: Dao = inject(Dao);
public create(entity: any) {
return this.dao.create(entity);
}
}
Stubbing dependency is easy :
import {Injectable} from 'injects';
import * as sinon from 'sinon';
Injectable('Dao', sinon.stub());
const service: Service = new Service();// will get stub dependency
service.create({ entityId: 1 });// will call the stub
Name of dependency's class is the key used to register the dependency instance.
npm install --save injects