Creating Factories before Container
If in some reason you need to define factories separatelly from the container declaration, you can just declare factories object of type IFactories<IContainer>.
Example 1. Declaring Factories Object
./factories.ts
import { IFactories } from 'true-di';
import { IContainer } from './interfaces';
import Logger from './Logger';
import DataSourceService from './DataSourceService';
import ECommerceService from './ECommerceService';
const factories: IFactories<IContainer> = {
logger: () =>
new Logger(),
dataSourceService: ({ logger }) =>
new DataSourceService(logger),
ecommerceService: ({ logger, dataSourceService }) =>
new ECommerceService(logger, dataSourceService),
};
export default factories;then we can use this factories object to create a container:
./index.js
Example 2. Partial Factories Object
You can define several factories objects those could be marged on the container creation stage.
./factories.ts
and use these factories to create a container:
./index.js
If some of partially declared factories contains a non-enumerable property, then use shallowMerge function instead of spread-operator.
Example 3. Direct Factory Declaration
Sometimes it could be convenient to declare just a factory for an item.
or
or even
and then use these factories to create container:
Caution
Despite pointed bellow way to declare factory seems concise:
but the consumers of the container became to be dependent on the interface of specific logger implementation, that could be wider then ILogger.
So, it is better to declare such factories in this way:
Last updated
Was this helpful?