If by DI you mean specific container and code that directly depends on this container then this code should only live in the entry point of you application. In your scenario, this is a Web layer. Or it can be a 'Main' procedure if this was a console app. This part of the application is referred to as Composition Root: 很容易理解,每个类都应通过其构造函数要求其依赖项,但这将将具有其依赖项的类组成的责任推给了第三方.那应该在哪里?在我看来,大多数人都渴望尽早撰写,但正确的答案是:尽可能靠近应用程序的入口点.As close as possible to the application’s entry point. 此位置称为应用程序的合成根",定义如下: Composition Root是应用程序中模块组成在一起的(最好是)唯一位置.A Composition Root is a (preferably) unique location in an application where modules are composed together. 这意味着所有应用程序代码仅依赖于构造函数注入(或其他注入模式),但从未组成.最终,只有在应用程序的入口处才构成整个对象图. 这篇关于在分层项目中放置依赖注入相关代码的最佳层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-12 19:15