gpt4 book ai didi

c# - 我需要在 Simple Injector 中注册具体的根类型吗?

转载 作者:行者123 更新时间:2023-11-30 23:08:22 24 4
gpt4 key购买 nike

阅读 Simple injector 文档以了解其工作原理,我阅读了以下段落。除了粗体部分,我明白它在解释什么。什么意思?

The technique for keeping this dependency to a minimum can be achieved by designing the types in your application around the constructor injection pattern: Define all dependencies of a class in the single public constructor of that type; do this for all service types that need to be resolved and resolve only the top most types in the application directly (i.e. let the container build up the complete graph of dependent objects for you)

忽略我对上面句子的缺乏理解,但在尝试为 Web api 设置简单注入(inject)器时遇到了这行代码 container.RegisterWebApiControllers(GlobalConfiguration.Configuration); 有了这个解释

Because controllers are concrete classes, the container will be able to create them without any registration.

这是否意味着如果我有一堆不依赖接口(interface)的类,我可以使用一行代码创建它们? (如果是这样,我应该怎么做)。

最佳答案

这意味着一个很好的做法是不依赖代码中的 DI 容器,除了一些您必须这样做才能“启动”应用程序的顶层。

这意味着您的所有类都将仅具有接口(interface)形式的构造函数依赖项,而不会执行 Container.Resolve。这只会在您的应用程序的顶层调用。

在某些框架中,您甚至不必自己这样做,因为这是框架运作方式的一部分。据我记得在 .Net 核心中,例如您不需要进行解析,但它会在 Controller 启动时在框架内发生。

Because controllers are concrete classes, the container will be able to create them without any registration.

这意味着您不必在容器中注册 Controller 本身。容器只会自己解析 Controller 依赖项,创建 Controller 并在其中传递所有已解析的依赖项。

附言仅在您的应用程序的根目录中解析对于 SimpleInjector 没有什么特别的。这是一个可以应用于任何容器的好做法,即使您不遵循它也可以使用 SimpleInjector,现在可能没有人会推荐它。

关于c# - 我需要在 Simple Injector 中注册具体的根类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com