Inversifyjs: Async Container Modules

Created on 23 Feb 2018  路  4Comments  路  Source: inversify/InversifyJS

In node.js, sometimes we need to initialize some async components before the application starts serving HTTP requests.

Currenr API

(async () => {

    const db = await getDbConn();

    let module = new ContainerModule(
        (bind: interfaces.Bind, unbind: interfaces.Unbind) => {
           bind("db").toContainerValue(db);
        }
    );

    let container = new Container();
    container.load(module);

    let server = new InversifyExpressServer(container);

    server.setConfig((app) => {
      // add body parser
       app.use(bodyParser.urlencoded({
         extended: true
      }));
      app.use(bodyParser.json());
    });

    let app = server.build();
    app.listen(3000);

})();

New API

The new API introduces 2 breaking changes:

- Container modules use now an async function
- The container.load method is now async

The new API introduces a new kind of module known as AsyncContainerModule and a new container method named loadAsync:

let module = new AsyncContainerModule(
    async (bind: interfaces.Bind, unbind: interfaces.Unbind) => { // async!
       const db = await getDbConn();
       bind("db").toContainerValue(db);
    }
);

(async () => {

    let container = new Container();
    await container.loadAsync(module); // await!

    let server = new InversifyExpressServer(container);

    server.setConfig((app) => {
      // add body parser
       app.use(bodyParser.urlencoded({
         extended: true
      }));
      app.use(bodyParser.json());
    });

    let app = server.build();
    app.listen(3000);

})();
minor

Most helpful comment

@sanex3339 see updated API. It will be blackguards compatible.

All 4 comments

If possible, keep old sync API please. My package is fully sync and i very don't want to make it async.

@sanex3339 see updated API. It will be blackguards compatible.

Amazing

Great !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

remojansen picture remojansen  路  4Comments

rashtao picture rashtao  路  3Comments

AriaFallah picture AriaFallah  路  4Comments

jshearer picture jshearer  路  4Comments

remojansen picture remojansen  路  3Comments