将服务注入另一个服务的最佳实践 [英] Best practice injecting service into another service

查看:28
本文介绍了将服务注入另一个服务的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我有两个实体(SubscriptionApplication),每个实体都有他的 Repository 层命名(SubscriptionRepositoryApplicationRepository)和两个 Service(ISubscriptionService)strong> 和 IApplicationService)

We suppose that I have Two Entity (Subscription and Application) and for each one his Repository layer named (SubscriptionRepository and ApplicationRepository) and two Service for each one (ISubscriptionService and IApplicationService)

在某些情况下,假设我们最终得到 ApplicationService 需要注入 SubscriptionService 的情况SubscriptionService 需要注入 ApplicationService 的情况(反过来),当然它是一个循环依赖

In some case, suppose we end up with a case where ApplicationService need to inject SubscriptionService and a case where SubscriptionService need to inject ApplicationService ( the reverse) and and of course it Is a Circular Dependency

我的问题是:

当我想将服务注入另一个服务时,我应该如何反思以免陷入此类问题.(这意味着我如何决定是否需要将 ApplicationService 注入 SubscriptionService 或相反)?

When I want to inject service into another how I should reflect to not fall into this type of problem. (it means how i can decide if i need to inject ApplicationService into SubscriptionService or the reverse)?

推荐答案

您可以通过使两个服务都依赖于另一个抽象来反转这两个服务的依赖关系.在您的情况下,由于两者都是域服务,您的实体或域服务发出的域事件可能非常适合.

You could invert the dependencies of both services to each other by making both depend on another abstraction instead. In your case, as both are domain services, domain events emitted by either your entities or the domain services could be a good fit.

但是如果不了解有关您的域的更多详细信息以及应用程序订阅的专用内容,就很难判断您是否面临设计问题.

But without knowing more details about your domain and what Application and Subscription are dedicated for it is hard to tell if you are not facing a design problem.

如果您认为存在设计缺陷,我建议您问自己这些问题,当我不确定自己是否在自己的设计中划定了正确的界限时,这些问题通常会对我有所帮助.领域模型.

If you think there is a design flaw I suggest to ask yourself these questions which often help me when I am not sure if I have drawn the correct boundaries in my domain model.

  • 将这两个相互依赖的组件合并是否更有意义?
  • 我的组件A是否访问了组件B的某些功能,而这些功能应该是组件A的一部分?
  • 我的组件B是否访问了组件A的某些功能,而这些功能应该是组件B的一部分?
  • A 或 B 的功能是否应该被另一个访问而不是在第三个尚未发现的组件中?这可能是另一个界面、领域事件或类似的东西......
  • Would it make more sense to merge these two components which are dependent on each other?
  • Does my component A access some feature of component B which should rather be part of component A?
  • Does my component B access some feature of component A which should rather be part of component B?
  • Should functionality of A or B which are accessed by the other rather be in a third not yet discovered component? This could be another interface, domain events or something similar...

这篇关于将服务注入另一个服务的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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