1
@injectable()
class Ninja implements Warrior {
    @inject(TYPES.Weapon) private _katana: Weapon;
    @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
    public fight() { return this._katana.hit(); }
    public sneak() { return this._shuriken.throw(); }
}
// file inversify.config.ts

import { Container } from "inversify";
import { TYPES } from "./types";
import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
import { Ninja, Katana, Shuriken } from "./entities";

const myContainer = new Container();
myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);

export { myContainer };

Take this code for example, how could one import Shuriken dynamically in order to code split?

I've been looking into hierarchical DI systems, provider injection, and Asynchronous container modules but none of it seems appropriate.

Shuriken could have other dependencies from di as well. so provider injection doesn't fit the bill.

hierarchical DI systems feels like that for every class that is intended to be loaded dynamically, a child container must be created.

How to split code in inversify?

icy0307
  • 11
  • 3

1 Answers1

0

I haven't tried this, but I think you can do:

let container = new Container();

// toDynamicValue isn't executed until the TYPES.ThrowableWeapon is requested
container.<ThrowableWeapon>(TYPES.ThrowableWeapon).toDynamicValue((context) => { 
  return new Promise((resolve){
    // where 'dependency' is a module that defines and returns an AsyncContainerModule
    // that file will need to load the dependencies for the AsyncContainerModule
    // but won't be loaded until this require is called.
    require('dependency').then((dep) => {
      await container.loadAsync(dep);
      resolve(container.get('Shuriken'));
    });
  });
});
thelastshadow
  • 3,406
  • 3
  • 33
  • 36