何时使用物业注入? [英] When to use property injection?

查看:128
本文介绍了何时使用物业注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 如果实例创建完全控制,我应该使用默认的构造函数注入吗?

  • 我使用构造函数注入我写入容器不可知代码吗?


  • 解决方案


    什么时候应该使用属性注入?


    如果依赖关系是真正可选的,您应该使用属性注入,当您具有本地默认值时,或当对象图包含循环依赖项时。



    属性注入会导致时间耦合,并且在编写Business of Business应用程序时,您的依赖项不应该是可选的:您应该应用空对象模式



    您也不应使用本地默认,因为这会使测试,隐藏依赖关系,并且很容易忘记配置依赖关系。



    对象图表都不应具有循环依赖关系。这是您的应用程序设计中的一个问题的指示。


    如果实例创建完全受控,我应该使用默认的构造函数注入吗? p>

    是的。构造器注入是最好的方法。这使得很容易看出一个类有哪些依赖关系,使得有可能使依赖项需要,并且可以防止时间耦合。


    我是正确的使用构造函数注入我写容器不可知代码?


    这是正确的。构造器注入允许您延迟使用哪个DI库的决定,并是否使用DI图书馆


    1. When should I use property injection?
    2. Should I use by default constructor injection if instance creation in fully controlled?
    3. Am I right that using a constructor injection I write container-agnostic code?

    解决方案

    When should I use property injection?

    You should use property injection in case the dependency is truly optional, when you have a Local Default, or when your object graph contains a cyclic dependency.

    Property Injection however causes Temporal Coupling and when writing Line of Business applications, your dependencies should never be optional: you should instead apply the Null Object pattern.

    Neither should you use a Local Default, since this complicates testing, hides the dependency, and makes it very easy to forget to configure the dependency.

    Neither should object graphs have cyclic dependencies. This is an indication of a problem in your application design.

    Should I use by default constructor injection if instance creation in fully controlled?

    Yes. Constructor injection is the best way. It makes it very easy to see which dependencies a class has, makes it possible to make dependencies required, and prevents Temporal Coupling.

    Am I right that using a constructor injection I write container-agnostic code?

    This is correct. Constructor injection allows you to delay the decision of which DI library to use, and whether at all you use a DI library.

    这篇关于何时使用物业注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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