From 5c241d8be4fb40f30635d7b4f8c0470e78effa1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Pintos=20L=C3=B3pez?= Date: Tue, 31 Dec 2024 18:44:28 +0100 Subject: [PATCH] feat(inversify-code-examples): add container module example --- .../containerModuleApiExample.int.spec.ts | 10 ++++ .../src/examples/containerModuleApiExample.ts | 59 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.int.spec.ts create mode 100644 packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.ts diff --git a/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.int.spec.ts b/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.int.spec.ts new file mode 100644 index 00000000..02f89885 --- /dev/null +++ b/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.int.spec.ts @@ -0,0 +1,10 @@ +import { describe, expect, it } from '@jest/globals'; + +import { Ninja, ninja, Shuriken } from './containerModuleApiExample'; + +describe('ContainerModule API', () => { + it('should provide expected service', async () => { + expect(ninja).toBeInstanceOf(Ninja); + expect(ninja.weapon).toBeInstanceOf(Shuriken); + }); +}); diff --git a/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.ts b/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.ts new file mode 100644 index 00000000..f81bd035 --- /dev/null +++ b/packages/docs/tools/inversify-code-examples/src/examples/containerModuleApiExample.ts @@ -0,0 +1,59 @@ +import { + Container, + ContainerModule, + inject, + injectable, + interfaces, + named, +} from 'inversify'; + +interface Weapon { + damage: number; +} + +@injectable() +export class Katana implements Weapon { + public readonly damage: number = 10; +} + +@injectable() +export class Shuriken implements Weapon { + public readonly damage: number = 5; +} + +@injectable() +export class Ninja { + @inject('Weapon') + @named('Ranged') + public readonly weapon!: Weapon; +} + +// Begin-example +const warriorsModule: ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + bind('Ninja').to(Ninja); + }, +); + +const weaponsModule: ContainerModule = new ContainerModule( + ( + bind: interfaces.Bind, + _unbind: interfaces.Unbind, + _isBound: interfaces.IsBound, + _rebind: interfaces.Rebind, + _unbindAsync: interfaces.UnbindAsync, + _onActivation: interfaces.Container['onActivation'], + _onDeactivation: interfaces.Container['onDeactivation'], + ) => { + bind('Weapon').to(Katana).whenTargetNamed('Melee'); + bind('Weapon').to(Shuriken).whenTargetNamed('Ranged'); + }, +); + +const container: Container = new Container(); +container.load(warriorsModule, weaponsModule); + +const ninja: Ninja = container.get('Ninja'); +// End-example + +export { ninja };