这是 this SO post 的重新措辞.
我发现使用中介模式可以有效减少 Controller 中的参数数量。
然后我开始怀疑这是否是情感领域服务。
但这不会隐藏服务的依赖关系吗?
我记得在某处读过,如果我注入(inject)了一堆依赖项,我可能有一个更大的域概念,可以封装在自己的服务中。我发现这是一种有效的模式。
那么,如何减少业务层服务中构造函数参数的数量呢?
最佳答案
太多的构造函数参数会产生代码异味,并且通常表示违反了单一职责原则 - 因此您需要注意 SOLID 中的“S”代码库。
构造函数参数是一个依赖项。通过使用调解器“解决”问题,您仍然拥有相同数量的依赖项,只是构造函数参数更少。您本质上是从可见的 SRP 代码气味转变为隐藏的 SRP 代码气味 - 这并不是真正的进步。
改善“太多依赖项”的情况
This blog post讨论这个确切的问题并用一个例子来支持它。
改善情况的基本方法是找到围绕一组依赖项聚集的代码,并将该代码提取到新的服务类中:
- Analyze how dependencies interact to identify clusters of behavior.
- Extract an interface from these clusters.
- Copy the original implementation to a class that implements the new interface.
- Inject the new interface into the consumer.
- Replace the original implementation with a call the new dependency.
- Remove the redundant dependencies.
关于c# - 如何减少 Controller 和业务层服务中构造函数参数的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40359513/