Patterns and Tips
Make lazy simple
Section titled “Make lazy simple”Prefer functions over eager init. Why? This will make the app lazy, hence faster.
// GoodcreateContainer().add({ eventBus: () => new EventBus(), userAuthService: () => new UserAuthService(),})
// Meh...createContainer().add({ eventBus: new EventBus(), userAuthService: new UserAuthService(),})
In the second example we create instances on IoC container start. Which in most cases is not desirable. With the first example, we use functions, and they will be executed only when requested
Lifecycle
Section titled “Lifecycle”Single Instance (a.k.a. Singleton)
let node = createContainer().add({ oven: () => new Oven(),})node.get("oven") === node.get("oven") // true
Transient
let node = createContainer().add({ oven: () => () => new Oven(),})node.get("oven") === node.get("oven") // false
Dynamic Imports
Section titled “Dynamic Imports”export async function provideKitchenContainer() { const { Kitchen } = await import("./kitchen/kitchen") return { kitchen: () => new Kitchen(), oven: async () => { const { Oven } = await import("./kitchen/oven") const oven = new Oven() await oven.preheat() return oven }, }}
import { createContainer } from "iti"import { provideKitchenContainer } from "./kitchen"let node = createContainer().add({ kitchen: async () => provideKitchenContainer(),})
// Next line will load `./kitchen/kitchen` moduleawait node.items.kitchen
// Next line will load `./kitchen/oven` moduleawait node.items.kitchen.oven
Tip: Prefer callbacks over of strings (in progress)
Section titled “Tip: Prefer callbacks over of strings (in progress)”If you use callback pattern across your app, you will be able to mass rename your containerKeys using typescript. With strings, you will have to manually go through the app. But even if you use string literals compiler will not compile until you fix your rename manually across the app.
const node = createContainer().addNode({ a: "A", b: "B",})
await node.get((containerKeys) => containerKeys.a) // BEST!!!await node.get("a") // it will work but...
Anti Patterns
Section titled “Anti Patterns”in progress
Known issues
Section titled “Known issues”TS2589: Type instantiation is excessively deep and possibly infinite
Section titled “TS2589: Type instantiation is excessively deep and possibly infinite”This bug is caused by a TS hard limit on 50 instantiationDepth
.
https://github.com/i18next/react-i18next/issues/1417 https://github.com/microsoft/TypeScript/issues/34933
As a quick workaround we suggest:
- Reduce the number of
.add
steps - this will help in most cases - Reduce the number of unique tokens - group some tokens together
- Create multiple containers - it seems that your app is getting pretty big and complex. Maybe create to 2 containers via
createContainer
? - Upgrade to TS 4.5 or higher
- Optimize ITI