true-di
true-di
is a Simple Dependency Injection Container for TypeScript and JavaScript
Installation
npm i --S true-di
yarn add true-di
Documentation
Read Documentation on Git Book
Usage Example:
./src/container.ts
import diContainer from 'true-di';
import { IContainer } from './interfaces';
import Logger from './Logger';
import DataSourceService from './DataSourceService';
import ECommerceService from './ECommerceService';
const container = diContainer<IContainer>({
logger: () =>
new Logger(),
dataSourceService: ({ logger }) =>
new DataSourceService(logger),
ecommerceService: ({ logger, dataSourceService }) =>
new ECommerceService(logger, dataSourceService),
});
export default container;
./src/controller.ts
import Express from 'express';
export const getOrders = async (req: Express.Request, res: Express.Response) => {
const { ecommerceService } = req.container;
res.json(
await ecommerceService.getOrders()
);
}
./src/index.ts
import express from 'express';
import container from './container';
import { getOrders } from './controller';
const app = express();
app.use((req, res, next) => {
req.container = container;
next();
});
app.get('/orders', getOrders);
app.listen(8080);
Why true-di
?
- It's light and idiomatic.
- It works with JavaScript and TypeScript.
- It's well-typed. Items types are always known whenever your code assess them.
- It is Isomorphic: works on Back end and on Front end.
- It works with Classes and with Closures.
- It doesn't require decorators (annotations).
- It doesn't depend on
reflect-metadata
. - It allows referring items without strings or other artificial elements.
- It uses
getters
under the hood. - It's lazy: container doesn't create an item until your code requests
- It automatically resolves dependencies
- It immediately falls down on constructor-injection of cyclic dependency
- It supports property-, setter- cyclic dependencies
- It doesn't know anything about context but it could be easily placed into the context.
- Its containers are composable.
- It's SOLID-compatible.
- It's more SOLID-compatible then other IOC solutions. Your code doesn't need to depend on the container (nor even on its interface).
- It's testable.
- It supports symbolic names.
- It doesn't have any other dependencies (and it will be kept)