javascripttypescriptinversifyjs

Middleware of inversify is called only once


I bind objects by inversify as below:

container.applyMiddleware(loggerMiddleware);

let module = new ContainerModule((bind: interfaces.Bind) => {
    bind<Logger>(TYPES.Logger).toConstantValue(logger);
    bind<ILoggerFactory>(TYPES.ILoggerFactory).to(WinstonLoggerFactory);

    bind<string>(TYPES.ConnectionString).toConstantValue(cs);
    bind<{}>(TYPES.ConnectionOptions).toConstantValue({});

    bind<ITradeController>(TYPES.ITradeController).to(TradeController);
    bind<ITradeService>(TYPES.ITradeService).to(TradeService).whenInjectedInto(TradeController);
    bind<ITradeRepository>(TYPES.ITradeRepository)
      .to(TradeMongoRepository)
      .whenInjectedInto(TradeService);

    bind<IUserService>(TYPES.IUserService).to(UserService).whenInjectedInto(TradeService);
    bind<IUserRepository>(TYPES.IUserRepository)
      .to(UserMongoRepository)
      .whenInjectedInto(UserService);
  });

container.load(module);

and also I declare an inversify middleware as below:

import * as inversify from 'inversify';

function logger(next: inversify.interfaces.Next): inversify.interfaces.Next {
  return (args: inversify.interfaces.NextArgs) => {
    let start = new Date().getTime();
    let result = next(args);
    let end = new Date().getTime();
    console.log(`wooooo  ${end - start}`);
    return result;
  };
}

export default logger;

when the application is run, only one message 'wooooo ' is printed.

for example, if I call services as below:

const tradeController = container.get<ITradeController>(TYPES.ITradeController);
const result = await tradeController.findByUserId(params.userId);

and tradeController call tradeService and then tradeService call tradeRepository and so on I expect that I see the message 'woooooo' for each level but it prints only once.

what's wrong?


Solution

  • Middlewares of inversify are called only once and their functionalities are different from AOP interceptors and this is why they are called only once.