15

In InversifyJS, are there any specific advantages of following the approaches outlined in factory injection guide and constructor injection guide for injecting factories and constructors respectively over just using toDynamicValue.

lorefnon
  • 12,875
  • 6
  • 61
  • 93

1 Answers1

35

toConstructor

If you use a toConstructor you will be able to pass arguments to the constructor but you won't be able to resolve those arguments (unless you inject them as well).

container.bind<interfaces.Newable<Katana>>("Newable<Katana>")
         .toConstructor<Katana>(Katana);

toDynamicValue

If you use a toDynamicValue you will be able to pass constructor arguments to the constructor and resolve those arguments using the context.

container.bind<Katana>("Katana")
        .toDynamicValue((context: interfaces.Context) => {
             return new Katana(context.container.get("SomeDependency")); 
        });

toFactory

If you use a toFactory you will be able to pass constructor arguments to the constructor and resolve those arguments using the context but you will also be able to produce different outputs based on factory arguments.

container.bind<interfaces.Factory<Weapon>>("Factory<Weapon>")
         .toFactory<Weapon>((context: interfaces.Context) => {
             return (throwable: boolean) => {
                 if (throwable) {
                     return context.container.getTagged<Weapon>(
                         "Weapon", "throwable", true
                     );
                 } else {
                     return context.container.getTagged<Weapon>(
                         "Weapon", "throwable", false
                     );
                 }
             };
         });
Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93
  • 2
    Thanks a lot for the clear and lucid explanation. Also thank you for all the awesome work on inversify. – lorefnon Nov 01 '17 at 19:07