0

Everytime I'm calling an api in inversify-express server the dependency is creating a new object everytime

var kernel=new Kernel();
kernel.bind<interfaces.Controller>(TYPE.Controller).to(SyncController).whenTargetNamed(TAGS.SyncController);
kernel.bind<DB_SyncDataDAO>(TYPES.DB_SyncDataDAO).to(DB_SyncDataDAO_Impl);
kernel.bind<SyncService>(TYPES.SyncService).to(SyncService_Impl);

Whenever I'm calling an api it is creating new object of each dependency everytime

Archit Dwivedi
  • 416
  • 4
  • 9

1 Answers1

0

I assume that you want some of the dependencies in your object graph to be singletons. You can do that using inSingletonScope when declaring a binding:

kernel.bind<interfaces.Controller>(TYPE.Controller)
      .to(SyncController)
      .whenTargetNamed(TAGS.SyncController)
      .inSingletonScope();

kernel.bind<DB_SyncDataDAO>(TYPES.DB_SyncDataDAO)
      .to(DB_SyncDataDAO_Impl)
      .inSingletonScope();

kernel.bind<SyncService>(TYPES.SyncService)
      .to(SyncService_Impl)
      .inSingletonScope();

As a side note (not related to your question) if DB_SyncDataDAO_Impl is an instance (nota class) then you should use

kernel.bind<T>("T").toConstantValue(instanceOfT)

Instead of:

kernel.bind<T>("T").to(classWhichIsAnImplementationOfT)

When you use toConstantValue, inSingletonScope is not required because constant values behave as singletons by default.

Hope it helps :)

Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93