在分层项目中放置依赖注入相关代码的最佳层 [英] best layer for placing dependency injection related code in layered project

本文介绍了在分层项目中放置依赖注入相关代码的最佳层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算在新应用程序中采用洋葱体系结构.

I am planning to follow onion architecture for my new application.

解决方案层次结构如下

  • 域-定义了服务和存储库的所有接口的地方.
  • 基础结构-这是放置所有数据访问权限的层.这些类通常实现在域中定义的接口.
  • Web-这是我的应用程序演示部分.在同一层内部,我有一个单独的文件夹,用于实现域中定义的服务.

我的计划是使用依赖性注入来解决依赖性.最初,我想到了将与DI相关的代码放置在Infrastructure中.但是问题在于,在映射服务时会导致循环引用,因为实际的服务实现在我的Web项目中,并且该Web项目已经在引用基础结构.我不能将具体服务移到另一层,因为它违反了Onion Architecture的原则(可传递依赖项).

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).

感谢任何潜在客户.

推荐答案

答案取决于您如何定义与DI相关的代码".

The answer depends on how you define 'DI related code'.

如果将DI定义为促进关注点之间松散耦合和分离的一组原理和模式,则应将这些模式(例如,构造函数注入)应用于应用程序的所有层.就像您将应用SOLID原则和其他OO最佳实践一样.

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.

如果用DI表示特定的容器和直接依赖于此容器的代码,则此代码应仅存在于应用程序的入口点.在您的方案中,这是一个Web层.或者,如果这是一个控制台应用程序,则可能是一个主要"过程.该应用程序的这一部分称为组合根:

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.

这意味着所有应用程序代码仅依赖于构造函数注入(或其他注入模式),但从未组成.最终,只有在应用程序的入口处才构成整个对象图.

这篇关于在分层项目中放置依赖注入相关代码的最佳层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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