In Inversify, why to prefer Constructor/Factory injection over toDynamicValue?

守給你的承諾、 提交于 2019-12-04 09:36:39

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
                     );
                 }
             };
         });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!