【问题标题】:In Inversify, why to prefer Constructor/Factory injection over toDynamicValue?在 Inversify 中,为什么更喜欢构造函数/工厂注入而不是 toDynamicValue?
【发布时间】:2018-04-02 16:58:57
【问题描述】:

在InversifyJS 中,遵循factory injection guide 和constructor injection guide 中概述的方法分别注入工厂和构造函数比仅使用toDynamicValue 有什么具体优势吗?

【问题讨论】:

    标签: typescript dependency-injection inversifyjs


    【解决方案1】:

    toConstructor

    如果您使用toConstructor,您将能够将参数传递给构造函数,但您将无法解析这些参数(除非您也注入它们)。

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

    toDynamicValue

    如果您使用toDynamicValue,您将能够将构造函数参数传递给构造函数并使用context 解析这些参数。

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

    到工厂

    如果您使用toFactory,您将能够将构造函数参数传递给构造函数并使用context 解析这些参数,但您还可以根据工厂参数生成不同的输出。

    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
                         );
                     }
                 };
             });
    

    【讨论】:

    • 非常感谢您提供清晰明了的解释。还要感谢您在 inversify 上所做的所有出色工作。
    猜你喜欢
    • 2018-05-26
    • 2012-03-27
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多