问题描述
我计划在我的新应用程序中遵循洋葱架构.
解决方案层次如下
- 域 - 定义服务和存储库的所有接口.
- 基础设施 - 这是所有数据访问所在的层.这些类通常实现域中定义的接口.
- Web - 这是我的应用程序演示部分.在同一层内,我有一个单独的文件夹用于实现域中定义的服务.
我的计划是使用依赖注入进行依赖解析.最初,我想在基础设施中放置与 DI 相关的代码.但问题是在我映射服务时会导致循环引用,因为实际的服务实现在我的 web 项目中,并且 web 项目已经在引用基础设施.我无法将具体服务移到另一层,因为它违反了洋葱架构的原则(传递依赖).
感谢任何线索.
答案取决于您如何定义DI 相关代码".
如果您将 DI 定义为一组促进松散耦合和关注点分离的原则和模式,那么这些模式(例如构造函数注入)应该应用于应用程序的所有层.就像您将应用 SOLID 原则和其他面向对象的最佳实践一样.
如果 DI 是指直接依赖于该容器的特定容器和代码,那么该代码应该只存在于您的应用程序的入口点中.在您的场景中,这是一个 Web 层.或者,如果这是一个控制台应用程序,它可以是一个主要"程序.这部分应用程序称为组合根:>
很容易理解,每个类都应该通过其构造函数要求其依赖项,但这将组合类及其依赖项的责任推给了第三方.那应该在哪里?在我看来,大多数人都渴望尽早作曲,但正确答案是:
尽可能靠近应用程序的入口点.
这个地方叫做应用程序的组合根,定义如下:
组合根是应用程序中一个(最好)唯一的位置,用于将模块组合在一起.
这意味着所有应用程序代码仅依赖于构造函数注入(或其他注入模式),但从未组合过.只有在应用程序的入口点才最终组成整个对象图.
I am planning to follow onion architecture for my new application.
the solution hierarchy is as follows
- Domain - where all the interfaces for the services and repositories defined.
- Infrastructure - this is the layer where all data access is placed. these classes typically implement interfaces defined in the domain.
- Web - this is my presentation part of the application. inside the same layer, I have a separate folder for implementing the services defined in the domain.
My plan is to use Dependency injection for dependency resolution. Initially, I thought of placing DI-related code in Infrastructure. But the problem is it leads to circular references while I map services Because the actual service implementation is in my web project and the web project is referencing Infrastructure already. I can't move concrete services to another layer because it violates the principles of Onion Architecture ( transitive dependencies).
Any lead is appreciated.
The answer depends on how you define 'DI related code'.
If you define DI as a set of principles and patterns that promote loose coupling and separation of concerns then these patterns (like Constructor Injection for example) should be applied at all layers of the application. Just like you would apply SOLID principles and other OO best practices.
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:
这篇关于在分层项目中放置依赖注入相关代码的最佳层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!