DI容器是否需要自己实例化对象才能使用构造函数注入? [英] Do DI Containers need to instantiate the object themselves in order to use constructor injection?

查看:76
本文介绍了DI容器是否需要自己实例化对象才能使用构造函数注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者不是自己创建对象,而是以某种方式 intercept 挂钩对象创建(例如,由MVC框架实例化的Controller)并传递任何内容他们需要依赖吗?

Or instead of creating the object themselves, do they somehow intercept or hook into object creation (for example, a Controller instantiated by the MVC framework) and pass in whatever dependencies they're required to?

我意识到在创建对象时他们需要做某事以使用构造函数注入,但是我不清楚容器是否

I realize they need to do something when the object is created in order to use constructor injection, but I am unclear as to whether the containers need to do the creating, or if they somehow intercept the object's creation.

无论答案是什么,所有的DI容器都这样做吗?

Whatever the answer is, do all DI containers do it this way?

我意识到这个问题对于大多数熟悉StructureMap,Unity,Ninject等工具的人来说可能是显而易见的...但是我是新手,意识到我并不真正了解它们如何在下面工作封面。我已经在Internet上搜索了,找不到合适的答案。

I realize this question is probably obvious to most familiar with tools like StructureMap, Unity, Ninject, etc... but I am new to them and realized I don't really know how they work under the covers. I have scoured the internet and can't find a good answer.

推荐答案

在我使用过的所有DI / IoC容器中,容器会自己创建。您将不会使用 new Something(dependency1,dependency2)找到任何生产代码。相反,您将隐式或显式地向容器询问 某事(可能是由于其他原因)。然后,容器根据配置的方式(以及注释方式 Something 的使用方式)重用 Something 的实例。 )。

In all the DI/IoC containers I've used, the containers do the creating themselves. You won't find any production code using new Something(dependency1, dependency2)... instead, you'll have code implicitly or explicitly asking the container for "an instance of Something" (maybe as a dependency of something else). The container then takes care of either reusing an instance of Something, based on how it's configured (and how Something is annotated).

在哪里经常调用,构造函数正在测试某事,此时容器可能根本不存在-或您可能具有特定于测试的配置,该配置使您可以以库存方式询问某些依赖项,并可能以特定于测试的方式提供其他依赖项。 (在某些情况下,您 still 无需显式调用构造函数...如果您具有容器的测试配置,例如对所有内容使用假存储,那么您可能仍然只需要要求在测试中使用某事的实例。)

Where you do often explicitly call the constructor is in the test for Something, at which point the container may well not exist at all - or you may have a test-specific configuration which allows you to ask for some of the dependencies in a stock way, and maybe provide other dependencies in a test-specific way. (In some cases, you still won't need to call the constructor explicitly... if you have a test configuration for the container, e.g. using fake storage for everything, then you may still just need to ask for an instance of Something to use in your tests.)

这篇关于DI容器是否需要自己实例化对象才能使用构造函数注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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