在Inverseify中,为什么相对于DynamicValue更喜欢使用Constructor / Factory注入? [英] In Inversify, why to prefer Constructor/Factory injection over toDynamicValue?

查看:117
本文介绍了在Inverseify中,为什么相对于DynamicValue更喜欢使用Constructor / Factory注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

InversifyJS 中,遵循工厂注入指南构造函数注入指南,仅通过使用 toDynamicValue

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.

推荐答案

toConstructor



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

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



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

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



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

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

这篇关于在Inverseify中,为什么相对于DynamicValue更喜欢使用Constructor / Factory注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆