Skip to content

Commit

Permalink
feat(inversify-code-examples): add container module example
Browse files Browse the repository at this point in the history
  • Loading branch information
notaphplover committed Dec 31, 2024
1 parent 66d8736 commit 5c241d8
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
});
});
Original file line number Diff line number Diff line change
@@ -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>('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<Katana>('Weapon').to(Katana).whenTargetNamed('Melee');
bind<Shuriken>('Weapon').to(Shuriken).whenTargetNamed('Ranged');
},
);

const container: Container = new Container();
container.load(warriorsModule, weaponsModule);

const ninja: Ninja = container.get('Ninja');
// End-example

export { ninja };

0 comments on commit 5c241d8

Please sign in to comment.